Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Broken getindex with no arguments #3313

Closed
blegat opened this issue Apr 5, 2023 · 2 comments · Fixed by #3314
Closed

Broken getindex with no arguments #3313

blegat opened this issue Apr 5, 2023 · 2 comments · Fixed by #3314

Comments

@blegat
Copy link
Member

blegat commented Apr 5, 2023

The syntax x[] works if x has only one element:

julia> x = [1]
1-element Vector{Int64}:
 1

julia> x[]
1

julia> x = [1, 2]
2-element Vector{Int64}:
 1
 2

julia> x[]
ERROR: BoundsError: attempt to access 2-element Vector{Int64} at index []
Stacktrace:
 [1] throw_boundserror(A::Vector{Int64}, I::Tuple{})
   @ Base ./abstractarray.jl:703
 [2] checkbounds
   @ ./abstractarray.jl:668 [inlined]
 [3] _getindex
   @ ./abstractarray.jl:1273 [inlined]
 [4] getindex(::Vector{Int64})
   @ Base ./abstractarray.jl:1241
 [5] top-level scope
   @ REPL[4]:1

This doesn't work anywork for a vector with JuMP types because of #3237
This broke DiffOpt for instance: jump-dev/DiffOpt.jl#238

@odow
Copy link
Member

odow commented Apr 5, 2023

I don't understand why x[] is meant to work iff there is one element. Is that intended behavior in Julia? Is it documented?

@blegat
Copy link
Member Author

blegat commented Apr 11, 2023

I can see it being useful in case you want to access the first element and have your code error in case there is more than one element. It's also the syntax for dereferencing a Ref so if you think of a Vector as a pointer to the first element it kind of makes sense

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

2 participants