awelkie
awelkie

Reputation: 2652

Is there a generic way of accessing a container of mutable elements?

I would like to mutate elements in a container. The only thing I care about is the length of the container and the fact that the container's elements are ordered (i.e. there is a first element, a second element, etc.). But I'm struggling to do this.

My first attempt was to use an Iterator of mutable references:

fn mutate<'a, A, I>(items: I) where I: Iterator<&'a mut A>

The problem is that I need to iterate more than once over the elements. But to avoid aliasing mutable references, structs like Slice's IterMut don't implement Clone or RandomAccessIterator. So as far as I know, I can't use the same iterator to iterate over mutable references more than once.

So then I looked at the IndexMut trait. This seems to be what I want, but I can't find another trait that specifies the length of a container. And the Slice struct that implements IndexMut does bounds checking for each access, which is undesirable.

So is there a way to do what I want? It would be nice to use Iterators, since what I really want to do is to iterate over the mutable elements several times.

Upvotes: 3

Views: 194

Answers (1)

Simon Sapin
Simon Sapin

Reputation: 10180

You can require more bounds:

fn mutate<'a, A, I>(items: I) 
where I: Iterator<Item=&'a mut A>,
      I: ExactSizeIterator,
      I: RandomAccessIterator,
      I: Clone {

Upvotes: 1

Related Questions