Composite types in Julia: dictionaries as a named field?

I would like to create a composite type that includes a dictionary as one of its named fields. But the obvious syntax doesn't work. I'm sure there is something fundamental that I don't understand. Here's an example:

type myType
    x::Dict()
end

      

Julia says: type: myType: in type definition, expected Type{T<:Top}, got Dict{Any,Any}

which means, I'm assuming the dictionary is not Any

, as any named field should be. But I'm not sure how to say what I mean.

I need a name that is a dictionary. The internal constructor initializes the dictionary.

+3


source to share


2 answers


There's a subtle difference in syntax between types and instances. Dict()

creates a dictionary, while Dict

itself is a type. When defining a composite type, the field definitions should be symbol::Type

.

This error message is a bit confusing. What he effectively says is this:



in the type definition, something expected with the type Type{T<:Top}

got an instance of the type Dict{Any,Any}

.

In other words, he expected something like Dict

which is Type{Dict}

, but instead got Dict()

which is Dict{Any,Any}

.

The syntax you want is this x::Dict

.

+7


source


Dict()

creates a dictionary in particular Dict{Any,Any}

(that is, keys and values ​​can be of any type <:Any

). You want the field to be of type Dict

, i.e

type myType
    x::Dict
end

      



If you know the types of keys and values, you can even write eg.

type myType
    x::Dict{Int,Float64}
end

      

+5


source







All Articles