This seems to only work due to essentially eliminating kwargs... in the MWE. Consider the following change, that breaks it again:
Base.@kwdef mutable struct MyStruct
id::Int
value::Symbol = :fixed
notimportant::Int = -1
end
MyStruct(id::Int, value::String, kwargs...) = MyStruct(id=id, value=Symbol(value), kwargs...)
MyStruct(id=1, value="a") # this fails again
While this certainly works, it achieves something else and does not solve the initial problem. It converts the String to a Symbol ahead of construction of the struct, instead of during. While this seems like a valid fix, consider the following:
- I have a large “data storage” (the
struct), that is initialized using data parsed from a file (yaml, csv, …). I read inStrings. This is fairly efficient for most fields. Later on I come to a point where profiling shows that keeping a specific field asSymbolmakes sense (due the timeloss of doingSymbol("somestring")after reading the data, usingSymbols can be worse thanStrings for many fields). - I construct this
structat several points of my code. If I need to “symbolify” a new field, I need to change this everywhere instead of at a single central point (the constructor).