Skip to content

Mutable indexing is strange. #17597

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

Closed
HeroesGrave opened this issue Sep 27, 2014 · 3 comments
Closed

Mutable indexing is strange. #17597

HeroesGrave opened this issue Sep 27, 2014 · 3 comments

Comments

@HeroesGrave
Copy link
Contributor

Mutably indexing a Vec (and probably lots of other collections) is weird.
On one hand, you can dereference a mutable pointer:

*vec.get_mut(index) = value;

Which is ugly and inconsistent with immutable indexing (vec[index])

With the new slicing syntax you can do this:

vec[mut][index] = value;

Which is arguably nicer. But wouldn't something like:

vec[mut index] = value;

Be even better and more consistent?

@ftxqxd
Copy link
Contributor

ftxqxd commented Sep 27, 2014

#12825 is preventing implementing IndexMut for Vec, HashMap, &c., but once that’s fixed, simply doing vec[index] = value; will work. The reason slicing uses an explicit mut but not indexing is because slicing directly returns a reference/slice (e.g., vec[a..b] returns &[T], vec[mut a..b] returns &mut [T]), while indexing just returns a value (e.g., vec[a] returns T). However, it doesn’t move the value out of the collection, it just dereferences a reference to it (i.e., vec[a] = *vec.index(&a) or *vec.index_mut(&a)). The problem is figuring out which of index and index_mut to use, which is represented by the issue #12825.

@HeroesGrave
Copy link
Contributor Author

Ah, okay. Thanks for clearing that up.

@ftxqxd
Copy link
Contributor

ftxqxd commented Nov 28, 2014

The vec[idx] = val; syntax now works for Vec, so I think this issue can be closed.

@Gankra Gankra closed this as completed Nov 28, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants