getfield(::Dict,val)

The following code (from here)

Base.getproperty(d::Dict, s::Symbol) = s ∈ fieldnames(Dict) ? getfield(d, s) : getindex(d, s)

makes a dictionary key symbols accessible like a struct fields, i.e.

julia> D = Dict(:a=>1,:x=>1.1,:arr=>[1,2,3],"str"=>2)
julia> D.x
1.1

However within REPL

julia> getfield(D,:x)
ERROR: type Dict has no field x
...

I want to understand why getfield(D,:x) does not work while it is working in the method implementation of Base.getproperty?

It doesn’t - the symbol is only forwarded to getfield if its indeed a field name. Otherwise the result of getindex (i.e. D[:x]) is returned.

1 Like

Oops … yes I see it now, it is fieldnames(Dict) (though even fieldnames(d) is also not defined)

That’s to be expected - fieldnames takes in a type, not an instance.