CPh*_*hil 4 dictionary abstract-data-type julia
我有一个抽象类型,带有子类型。我想制作并添加到包含子类型的 Dict 中。这是可行的吗?实现这一目标的更好方法是什么?
例子:
abstract type Cat end
struct Lion <: Cat
manecolour
end
struct Tiger <: Cat
stripewidth
end
cats = Dict{Int, <:Cat}()
Run Code Online (Sandbox Code Playgroud)
给
ERROR: MethodError: no method matching Dict{Int64,var"#s3"} where var"#s3"<:Cat()
Run Code Online (Sandbox Code Playgroud)
这样做更正确的方法是什么?
只需使用抽象类型作为容器类型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)
Run Code Online (Sandbox Code Playgroud)