Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an empty Dict where the values are the subtype of an abstract type

I've got an abstract type, with subtypes. I'd like to make and add to a Dict that holds the subtypes. Is this doable? What's a better way of achieving this?

Example:

abstract type Cat end

struct Lion <: Cat
   manecolour
end

struct Tiger <: Cat
   stripewidth
end

cats = Dict{Int, <:Cat}()

gives

ERROR: MethodError: no method matching Dict{Int64,var"#s3"} where var"#s3"<:Cat()

What's the more correct way of doing this?

like image 826
CPhil Avatar asked Mar 02 '23 03:03

CPhil


1 Answers

Just use the abstract type as the container type: 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)
like image 105
fredrikekre Avatar answered Apr 27 '23 02:04

fredrikekre