How to create structs with fields that are reserved Julia keywords

I do not seem to be able to create structs that have reserved Julia keywords as fields
Essentials · The Julia Language

For example:

struct test
   local::Float64
end

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()
println(tmp.local)

see var"name"
https://docs.julialang.org/en/v1/base/base/#var"name"

julia> struct test
          var"local"::Float64
       end

julia> tmp = test(1.2)
test(1.2)

julia> tmp.local
1.2

julia> tmp.var"local"
1.2
5 Likes

See the explanation of var"name"

Input

struct Foo
    var"local"::Float64
end
@show foo = Foo(1.2)
@show foo.local;

Output

foo = Foo(1.2) = Foo(1.2)
foo.local = 1.2

Input (how to look at the parser result of the code above.)

:(struct Foo
    var"local"::Float64
end) |> Base.remove_linenums! |> print

Output

struct Foo
    local::Float64
end

Edit: Wow! It’s a coincidence that the numbers in the two examples are both 1.2!

2 Likes

Here’s an alternative approach, which is more verbose, but perhaps more familiar-looking:

struct Test
    _local::Float64
end
function Base.getproperty(t::Test, sym::Symbol)
    if sym == :local
        return t._local
    else
        return getfield(t, sym)
    end
end

jl> t = Test(1.2)
Test(1.2)

jl> t.local
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.

3 Likes

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.