Skip to content

Implement Index and IndexMut traits - #679

Merged
alejandro-vaz merged 1 commit into
servo:v2from
mikwielgus:v2
Sep 26, 2026
Merged

alejandro-vaz merged 1 commit into
servo:v2from
mikwielgus:v2

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, like this:

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.

I have added two tests to test these traits.

@alejandro-vaz alejandro-vaz 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.

wait... weren't they implemented already??

@alejandro-vaz

Copy link
Copy Markdown
Collaborator

rustfmt is complaining about styling, simply run cargo fmt --all

@alejandro-vaz

Copy link
Copy Markdown
Collaborator

I thought we had Index and IndexMut somewhere wtf

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

```
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.

I have added two tests to test these traits.
@mikwielgus

Copy link
Copy Markdown
Contributor Author

rustfmt is complaining about styling, simply run cargo fmt --all

Done. (I actually also had to point it to nightly Rust's rustfmt to work)

@alejandro-vaz

Copy link
Copy Markdown
Collaborator

thanks @mikwielgus, not sure how we missed this

@alejandro-vaz
alejandro-vaz added this pull request to the merge queue Sep 26, 2026
Merged via the queue into servo:v2 with commit b71ab5d Sep 26, 2026
8 checks passed
@mikwielgus

Copy link
Copy Markdown
Contributor Author

I thought we had Index and IndexMut somewhere wtf

Indexing and mutation of an indexed element obviously still worked without Index and IndexMut because of Deref coercion into slice, which actually does have Index and IndexMut implemented. This is why these traits are easy to miss for vec-like collections. I had the same issue with thin-vec.

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