Dictionary 定义一个空Dict,其中值是抽象类型的子类型
我有一个抽象类型,带有子类型。 我想制作并添加到保存子类型的Dict中。 这可行吗? 实现这一目标的更好方法是什么 例如:Dictionary 定义一个空Dict,其中值是抽象类型的子类型,dictionary,julia,abstract-data-type,Dictionary,Julia,Abstract Data Type,我有一个抽象类型,带有子类型。 我想制作并添加到保存子类型的Dict中。 这可行吗? 实现这一目标的更好方法是什么 例如: abstract type Cat end struct Lion <: Cat manecolour end struct Tiger <: Cat stripewidth end cats = Dict{Int, <:Cat}() 抽象类型Cat-end struct Lion只需使用抽象类型作为容器类型:cats=Dict{Int
abstract type Cat end
struct Lion <: Cat
manecolour
end
struct Tiger <: Cat
stripewidth
end
cats = Dict{Int, <:Cat}()
抽象类型Cat-end
struct Lion只需使用抽象类型作为容器类型:cats=Dict{Int,Cat}()
:
类型为数据类型
——但UnionAll
s除外。所以你可以
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
如果Cat
类型的数量较少,可以避免使用抽象容器来提高性能:
cats = Dict{Int, Cat}()
cats[1] = Lion(12)
cats2 = Dict{Int, Union{subtypes(Cat)...}}()
cats2[1] = Lion(12)
现在正在测试(我使用的是Tiger
和Lion
cat类型):
另见:
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
cats = Dict{Int, Cat}()
cats[1] = Lion(12)
cats2 = Dict{Int, Union{subtypes(Cat)...}}()
cats2[1] = Lion(12)
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)