Reputation: 469
I have written a function that adds an element to a NamedTuple:
function Base.setindex!(nt::NamedTuple, key::String, value::Any)
return (; nt..., key=value)
end
nt = (; a=1, b=2)
setindex!(nt, "c", 3)
The issue is though that the added value has the key "key", and not the actual string that key
represents as seen below:
(a = 1, b = 2, key = 3)
How can I "evaluate" the key
-variable before adding it to the NamedTuple?
Upvotes: 3
Views: 401
Reputation: 42214
You could also try using Accessors
. This is a Julia package providing a macro based syntax for working with immutable types. This syntax makes the code more readable.
julia> using Accessors
julia> nt = (;a=1, b=2)
(a = 1, b = 2)
julia> new_nt = @set nt.a = 33
(a = 33, b = 2)
julia> new_nt = @insert new_nt.c = 44
(a = 33, b = 2, c = 44)
Upvotes: 1
Reputation: 69879
This is how I would do it (note that this creates a new NamedTuple
and does not update the passed nt
as this is not possible):
julia> setindex(nt::NamedTuple, key::AbstractString, value) =
merge(nt, (Symbol(key) => value,))
setindex (generic function with 2 methods)
julia> setindex((a=1, b=2), "c", 3)
(a = 1, b = 2, c = 3)
julia> setindex((a=1, b=2), "b", 3) # note what happens if you re-use the key that is already present
(a = 1, b = 3)
Upvotes: 3