Julia 中的复合类型:作为命名字段的字典?

Composite types in Julia: Dictionaries as a named field?

我想制作一个包含字典作为其命名字段之一的复合类型。但是明显的语法不起作用。我敢肯定有一些基本的东西我不明白。这是一个例子:

type myType
    x::Dict()
end

Julia 说:type: myType: in type definition, expected Type{T<:Top}, got Dict{Any,Any} 这意味着,我猜,字典不是 Any 的字典,因为任何命名字段都必须是。但我不确定如何告诉它我的意思。

我需要一个作为字典的命名字段。内部构造函数将初始化字典。

Dict() 创建一个字典,特别是 Dict{Any,Any}(即键和值可以有任何类型,<:Any)。您希望字段的类型为 Dict,即

type myType
    x::Dict
end

如果您知道键和值类型,您甚至可以编写,例如

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

typesinstances 在语法上有细微差别。 Dict() 实例化字典,而 Dict 本身就是类型。定义复合类型时,字段定义需要采用 symbol::Type.

形式

该错误消息有点令人困惑。它的意思是:

in type definition, expected something with the type Type{T<:Top}, got an instance of type Dict{Any,Any}.

In other words, it expected something like Dict, which is a Type{Dict}, but instead got Dict(), which is a Dict{Any,Any}.

您想要的语法是 x::Dict.