【问题标题】:Define an empty Dict where the values are the subtype of an abstract type定义一个空字典,其中值是抽象类型的子类型
【发布时间】:2020-12-16 07:56:36
【问题描述】:
我有一个带有子类型的抽象类型。
我想制作并添加到包含子类型的 Dict 中。
这是可行的吗?
实现这一目标的更好方法是什么?
例子:
abstract type Cat end
struct Lion <: Cat
manecolour
end
struct Tiger <: Cat
stripewidth
end
cats = Dict{Int, <:Cat}()
给予
ERROR: MethodError: no method matching Dict{Int64,var"#s3"} where var"#s3"<:Cat()
这样做更正确的方法是什么?
【问题讨论】:
标签:
dictionary
julia
abstract-data-type
【解决方案1】:
只使用抽象类型作为容器类型:cats = Dict{Int, Cat}():
julia> cats = Dict{Int, Cat}()
Dict{Int64,Cat}()
julia> cats[1] = Lion(12)
Lion(12)
julia> cats
Dict{Int64,Cat} with 1 entry:
1 => Lion(12)
【解决方案2】:
类型是DataType - 除了UnionAlls。所以你可以这样做
julia> d = Dict{Int, Union{DataType, UnionAll}}()
Dict{Int64,Union{DataType, UnionAll}}()
julia> for (i, type) in enumerate(subtypes(Integer))
d[i] = type
end
julia> d
Dict{Int64,Union{DataType, UnionAll}} with 3 entries:
2 => Signed
3 => Unsigned
1 => Bool
【解决方案3】:
如果Cat 类型的数量很少,您可以避免使用抽象容器来提高性能:
cats = Dict{Int, Cat}()
cats[1] = Lion(12)
cats2 = Dict{Int, Union{subtypes(Cat)...}}()
cats2[1] = Lion(12)
现在测试(我正在使用Tiger 和Lion 猫类型):
julia> @btime $cats[1].manecolour == 12;
25.300 ns (0 allocations: 0 bytes)
julia> @btime $cats2[1].manecolour == 12;
17.434 ns (0 allocations: 0 bytes)