Safe IterMut With mem::take
Yield mutable references from a custom iterator without unsafe: mem::take swaps the remaining slice out, split_first_mut peels one element off the front.
Code
// 零 unsafe 的可变迭代器:mem::take 把剩余切片临时搬走,
// split_first_mut 拆出首元素,剩余部分再放回去
struct IterMut<'a, T> {
slice: &'a mut [T],
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
let (first, rest) = std::mem::take(&mut self.slice).split_first_mut()?;
self.slice = rest;
Some(first)
}
}
fn scale_all(values: &mut [f64], factor: f64) {
for v in IterMut { slice: values } {
*v *= factor;
}
}
fn main() {
let mut gains = vec![1.0, 2.0, 3.0, 4.0];
scale_all(&mut gains, 2.0);
for v in IterMut { slice: gains.as_mut_slice() } {
println!("{v:?}");
}
}The borrow trick inside next()
IterMut<'a, T> holds &'a mut [T], and next(&mut self) -> Option<&'a mut T> needs to hand out a borrow with lifetime 'a while self is only borrowed as &mut self — the direct move is forbidden. std::mem::take(&mut self.slice) replaces self.slice with an empty slice and yields the real one by value; split_first_mut()? then splits it into (first, rest), and self.slice = rest puts the remainder back. The ? on split_first_mut maps an empty slice to None, which is the iterator’s natural end — all of it safe code, zero unsafe.
What scale_all leaves behind
scale_all(values, factor) drives for v in IterMut { slice: values } with *v *= factor, so main’s gains = vec![1.0, 2.0, 3.0, 4.0] comes back doubled; the second loop prints each element through another IterMut:
2.0
4.0
6.0
8.0
One printed line per element, in order — the same iterator type both mutates and re-reads the slice.
The line that makes the swap legal
let (first, rest) = std::mem::take(&mut self.slice).split_first_mut()?;
mem::take is what lets first carry the 'a lifetime out of the method while self keeps a valid (empty, then restored) slice — the exchange happens inside one expression, so no moment exists where the struct observes itself empty except through take’s contract.
Interactive Tools for This Topic
FAQ
- How do you run Safe IterMut With mem::take?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.