[英]Dictionaries with strings as keys and any values
I am trying to define a dictionary that takes strings as keys and any values.我正在尝试定义一个将字符串作为键和任何值的字典。 Thus, I try to use
Dict{String, <:Any}
as type.因此,我尝试使用
Dict{String, <:Any}
作为类型。 However, the return value to that expression is但是,该表达式的返回值是
> Dict{String,#s27} where #s27
Moreover, if I try to define a dictionary of that type I get an error:此外,如果我尝试定义该类型的字典,则会出现错误:
Dict{String,<:Any}()
I get ERROR: MethodError: no method matching Dict{String,#s28} where #s28()
Dict{String,<:Any}()
我得到ERROR: MethodError: no method matching Dict{String,#s28} where #s28()
Dict{String,<:Any}("aa"=>42)
I get ERROR: MethodError: no method matching Dict{String,#s29} where #s29(::Pair{String,Int64})
Dict{String,<:Any}("aa"=>42)
我得到ERROR: MethodError: no method matching Dict{String,#s29} where #s29(::Pair{String,Int64})
I also tried using Dict{String}
(which should be equivalent), with similar results.我也尝试使用
Dict{String}
(应该是等效的),结果相似。
What am I missing about types of dictionaries here?我在这里缺少什么类型的字典?
What you are looking for is a Dict{String, Any}
, not Dict{String, <:Any}
.您正在寻找的是
Dict{String, Any}
,而不是Dict{String, <:Any}
。 The first one is a concrete type, namely a dict that takes strings as keys and anything as values.第一个是具体类型,即以字符串为键,以任何为值的字典。 The second,
Dict{String, <:Any}
is not actually a concrete type, but a unionall type.第二个,
Dict{String, <:Any}
实际上不是一个具体的类型,而是一个unionall类型。 That means it is an infinite set of types .这意味着它是一个无限的类型集。 And the error you are seeing is that you can't instantiate this set of types.
您看到的错误是您无法实例化这组类型。 You can only instantiate a concrete (leaf) type.
您只能实例化具体(叶)类型。
Another way of writing Dict{String, <:Any}
is Dict{String, T} where T <: Any
, and that makes it a little clearer what it is.另一种写
Dict{String, <:Any}
是Dict{String, T} where T <: Any
,这使它更清楚它是什么。 It is the set of all types of Dict
that has String
as they key type and a type that is a subtype of Any
as their value type.它是所有类型的
Dict
的集合,它们的键类型是String
,而值类型是Any
的子类型。
So for example we can say that Dict{String, Int}
is a subtype of the infinite set Dict{String, <:Any}
.例如,我们可以说
Dict{String, Int}
是无限集Dict{String, <:Any}
的子类型。
Edit: One use of unionall types is to be able to restrict the kind of type you take to fine grained level.编辑: unionall 类型的一种用途是能够将您采用的类型限制为细粒度级别。 For example, a counting function may look like this:
例如,一个计数函数可能如下所示:
function count_stuff(stuff, counter::Dict{T, <:Integer}) where T
# stuff here¨
end
The second argument here is a Dict
that has some subtype of Integer
as a value type and any type as a key type.这里的第二个参数是一个
Dict
,它有一些Integer
子类型作为值类型,任何类型作为键类型。 That's basically what you'd need to use the dict as a counter.这基本上就是您将 dict 用作计数器所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.