Use "end" as NamedTuple key or struct field

I wanted to use “end” as a key of NamedTuple, however:

julia> (start = 1, end = 2)
ERROR: syntax: unexpected "end"

While I understand “end” is a reserved keyword, I guess there is no ambiguity if it is inside parentheses so we may parse it correctly.

My current workaround is:

julia> NamedTuple{Tuple([:start, :end])}([1,2]).end
2

which is a little bit ugly.

Another case is to use “end” as a struct field, the workaround would be even more ugly:

struct Range
           start
           end_
end
function Base.getproperty(x::Range, symbol::Symbol)
       if symbol === :end
           getfield(x, :end_)
       else
           getfield(x, symbol)
       end
end

I am not sure about the struct field case, but I feel using arbitrary key for a named tuple would be a valid usage. Any opinions?

imo use of core tokens for other purposes is an anti-pattern
[the source text is not just for you today, it is for you in six months and, perhaps for others who – at first reading, prefer disambiguity]

5 Likes

Agree on the struct field case, but not named tuple.

Named tuple is used by people to represent Table rows (e.g. TypedTables.jl) and it should allow arbitrary key. As such (start = 1, end = 2) is much easier to read than NamedTuple{Tuple([:start, :end])}([1,2])

You can use the constructor

julia> NamedTuple{(:start,:end)}((1, 2))
(start = 1, end = 2)
5 Likes

I agree. Seems better, in this case particularly, to just use a different word. For example:

julia> (start = 1, stop = 2)
6 Likes
julia> a = 1:3;

julia> dump(a)
UnitRange{Int64}
  start: Int64 1
  stop: Int64 3

which is exactly what julia base does :wink:

3 Likes