Why can you write `r[1]` if `r` is a number?

I encountered an interesting bug here in OrbitalElements.jl. Essentially, writing r[1] returned r because r was a number (a Float64 specifically). This also works when writing numbers directly: you can write 42[1]. r[:] doesn’t work however.

I would expect this to result in an error, as it is most likely a programming error, and can’t see cases where it would be useful. Maybe it is consistent with eachindex(42) being Base.OneTo(1) ?

1 Like

not only you can do r[1], you can also

julia> r = 1
1

julia> r[1,1]
1

julia> r[1,1,1]
1

see:

https://docs.julialang.org/en/v1/manual/arrays/#Omitted-and-extra-indices

3 Likes
2 Likes

Thanks for pointing out this discussion! So this goes deeper than what I thought.

You can even do this

julia> r=1
1

julia> for k in r
       println(k)
       end
1
1 Like