I would like to define a Dict{A, Bool} and then put entries with keys of type B (a subtype of A) into it. Adding B entries to the Dict works, as does indexing the Dict with [], but get doesn’t seem to work:
julia> VERSION
v"1.8.2"
julia> abstract type A end; struct B <: A name end
julia> b = B("b")
B("b")
julia> d = Dict{A, Bool}(b => true)
Dict{A, Bool} with 1 entry:
B("b") => 1
julia> d[b]
true
julia> get(d, b)
ERROR: MethodError: no method matching get(::Dict{A, Bool}, ::B)
Closest candidates are:
get(::Dict{K, V}, ::Any, ::Any) where {K, V} at dict.jl:523
get(::IOContext, ::Any, ::Any) at show.jl:343
get(::WeakKeyDict{K}, ::Any, ::Any) where K at weakkeydict.jl:142
...
get(d, convert(A, b)) doesn’t seem to work either. Is there a way to make get work in this case?
help?> get
search: get get! getpid getkey getfield getindex getproperty gethostname get_zero_subnormals SegmentationFault mergewith mergewith! RegexMatch
get(collection, key, default)
Return the value stored for the given key, or the given default value if no mapping for the key is present.
│ Julia 1.7
│
│ For tuples and numbers, this function requires at least Julia 1.7.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> d = Dict("a"=>1, "b"=>2);
julia> get(d, "a", 3)
1
julia> get(d, "c", 3)
3
I thought there was a two argument get (though obviously I’ve never used it).
I’m using get because I can’t work out how to broadcast []: d.[[b, c]] doesn’t work so I resorted to get.(Ref(d), [b, c]). get.(Ref(d), [b, c], nothing) works, I just never use the nothing.