Hello!
Suppose I have a line as such:
varNames = NamedTuple{(:key,:offset,:type,:ncol), Tuple{String,Int,DataType,Int}}
The typeof this is:
typeof(varNames)
DataType
Then my question is; how do I insert values into, i.e. construct a NamedTuple based on this data type?
Kind regards
I don’t know why you want to do this, you’re probably looking for a struct
.
That said,
julia> varNames(("hi",3,String,4))
(key = "hi", offset = 3, type = String, ncol = 4)
2 Likes
Thanks!
I ended up doing it differently this time as you hinted at (dict, instead of struct), but knowledge is power, so thanks for sharing the correct way to do it! ![:blush: :blush:](https://emoji.discourse-cdn.com/twitter/blush.png?v=12)
Kind regards
That’s probably fine. Just wanted to point out that there are many advantages to a struct over a Dict for something like this, performance wise.
struct VarNames
key::String
offset::Int
type::DataType
ncol::Int
end
It gives you dispatch, clearer contract and more efficient storage than a Dict{Symbol, Any}
. If you’re willing to void the dispatch you could have also just used a NamedTuple
like you first suggested, but without the intermediate type alias:
x = (key="hi", offset=3, type=String, ncol=4)
But if it works it works.
4 Likes
You can’t insert values in a NamedTuple (or a Tuple for what does it matter), as these are immutable types, after they have been created you can’t modify them (you can still modify -but not reassign - mutable elements of it)
4 Likes