I do not seem to be able to create structs that have reserved Julia keywords as fields
Essentials · The Julia Language
will throw a
syntax: malformed expression error
Because I want to match an existing naming convention I do not have the freedom to choose whatever struct field names I’d like.
Is there any to create structs with fields that are reserved Julia keywords? I think it should be possible, after all something like the following syntax should not be confusing:
tmp = test()
julia> struct test
julia> tmp = test(1.2)
See the explanation of
@show foo = Foo(1.2)
foo = Foo(1.2) = Foo(1.2)
foo.local = 1.2
Input (how to look at the parser result of the code above.)
end) |> Base.remove_linenums! |> print
Edit: Wow! It’s a coincidence that the numbers in the two examples are both 1.2!
Here’s an alternative approach, which is more verbose, but perhaps more familiar-looking:
function Base.getproperty(t::Test, sym::Symbol)
if sym == :local
return getfield(t, sym)
jl> t = Test(1.2)
Mandating particular field names is questionable practice though, and the names shouldn’t really be part of an interface. Why is this done? Accessor functions are normally preferred.
Excellent! Thank you for pointing me to the
var keyword. That works beautifully for my application.
I’ll also think about developing accessor functions, but it is handy/easier to keep the same field names that were used in the original data structure that I am replicating in Julia.