If I have a local, mutable vector, I can partition it as follows, copied from the documentation of partition
.
let mut a = vec![1, 2, 3, 4];
let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter().partition(|&n| n % 2 == 0);
The a
vector is consumed (moved) in this process. However, the same call to partition doesn't work if I have a borrowed mutable reference. If I try to use the same code in that case, I get the error:
error[E0277]: the trait bound `std::vec::Vec<i32>: std::iter::Extend<&mut i32>` is not satisfied
--> src/main.rs:2:59
|
2 | let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter().partition(|n| **n % 2 == 0);
| ^^^^^^^^^ the trait `std::iter::Extend<&mut i32>` is not implemented for `std::vec::Vec<i32>`
|
= help: the following implementations were found:
<std::vec::Vec<T> as std::iter::Extend<&'a T>>
<std::vec::Vec<T> as std::iter::Extend<T>>
Based on How to make a Rust mutable reference immutable?, I wrote the following, which compiles and puts the right values into even
and odd
.
fn doit(a: &mut Vec<i32>) {
let (even, odd): (Vec<i32>, Vec<i32>) = (&*a).into_iter().partition(|&n| n % 2 == 0);
println!("even {:?}, odd {:?}, a {:?}", even, odd, a);
}
However, this does not consume the original vector, even though I'm using into_iter()
. There's something about mutability, borrowing, or iterators that I'm just not getting here.