Hi Julia users,
I was trying to extract multiple elements from a NamedTuple and Failed.
It works for extracting one element (pt here is a NamedTuple) through the following code line
But doesn’t work for extracting multiple elements, see below
Any suggestions? Thanks a lot.
obj = (a = 1, b = 2, c = 3)
a, b, c = obj.a, obj.b, obj.c
a, b, c = [ getproperty(obj, pn) for pn in propertynames(obj) ]
or using Parameters.jl
@unpack a, b, c = obj
Use three back-ticks (`) for formatting code in posts.
Or something like
julia> nt = (a = 1, b = 2, c = 3)
(a = 1, b = 2, c = 3)
julia> getproperty.(Ref(nt), [:a, :b])
but note that a
NamedTuple may not be the best match for this use case (you don’t get the inference advantages when the field names are provided dynamically, you might as well just use a
Dict or similar).