Skip to content

Implement Index and IndexMut traits - #98

Merged
emilio merged 1 commit into
mozilla:mainfrom
mikwielgus:main
Oct 7, 2026
Merged

emilio merged 1 commit into
mozilla:mainfrom
mikwielgus:main

Conversation

@mikwielgus

Copy link
Copy Markdown
Contributor

It's useful to have Index and IndexMut traits implemented if you want to have code that is generic over indexable containers, such as this one:

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 also consistent with Vec, which also implements them.

Immutable indexing is already tested, but I have added a test for mutable indexing.

It's useful to have `Index` and `IndexMut` traits implemented if you
want to have code that is generic over indexable containers, such as
this one:

```
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 also consistent with `Vec`, which also
implements them.

Immutable indexing is already tested, but I have added a test for
mutable indexing.

@emilio emilio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It matches Vec<> so I guess it seems fine. Thanks!

@emilio
emilio merged commit 4568732 into mozilla:main Oct 7, 2026
5 checks passed
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

Successfully merging this pull request may close these issues.

2 participants