The difference between VecDeque Iter and IterMut impl

#1

Hi, rustaceans, recently i read some std library vec_deque source code, i’m confused about:

Iter<'a,T> next() unsafe block
IterMut<'a,T> next() unsafe block

why IterMut next() method unsafe block can’t be written like
unsafe { Some(self.ring.get_unchecked_mut(tail)) }

current IterMut unsafe block , first get temporary mut ref , then convert to *mut T, then get back mut ref , why ?

0 Likes

#2

Casting to a raw pointer and back is a way to (unsefaly) cast a lifetime. You can’t get &'a mut T from &'a mut T, but you can get &'a mut T from *mut T for any 'a.

I think the cast is required because, without it, the resulting lifetime will be bound by both the lifetime of the iterator itself and the lifetime of the underlying VecDec. This is just my intuition though, I can’t give a precise explanation.

0 Likes

#3

Thanks for your explanation.

0 Likes