Repository navigation
Implement Index and IndexMut for Vec - #696
Conversation
8a64218 to
bc8fe8f
Compare
sgued
left a comment
There was a problem hiding this comment.
Thanks!
I didn't realise std::Vec implemented Index directly. The implementation looks good to me, please change the test and update the changelog.
bc8fe8f to
1e054b3
Compare
While it's already possible to use index syntax (e.g. `v[1]`) on `Vec`
due to `Deref` coercion into slice, it's nevertheless useful to have
`Index` and `IndexMut` traits implemented if you want to have code that
is generic over indexable containers via trait bounds, like in this
snippet:
```
fn increment<C>(container: &mut C, index: usize)
where
C: std::ops::IndexMut<usize>,
C::Output: std::ops::AddAssign<i32>,
{
container[index] += 1;
}
```
Having these traits is consistent with Rust standard library's `Vec`,
which also implements them.
There are also other collections that could implement `Index`
or `IndexMut`. If this PR is accepted, I will follow up with
implementations for these as well.
1e054b3 to
f70f19c
Compare
sgued
left a comment
There was a problem hiding this comment.
Why not the following? Using the trait seems correct but I'm curious, this seems more intuitive.
#[inline]
fn index(&self, index: I) -> &Self::Output {
&self.as_slice()[index]
}
I just have a habit of programming defensively when it comes to boilerplatey trait impls, as I ended up with infinitely recursive code a few times due to ambiguities in resolution. It's probably not needed, but it doesn't make a difference either way. |
|
Thanks, it also lt also makes it closer to the |
While it's already possible to use index syntax (e.g.
v[1]) onVecdue toDerefcoercion into slice, it's nevertheless useful to haveIndexandIndexMuttraits implemented if you want to have code that is generic over indexable containers via trait bounds, like in this snippet:Having these traits is consistent with Rust standard library's
Vec, which also implements them.There are also other collections that could implement
IndexorIndexMut. If this PR is accepted, I will follow up with implementations for these as well.