Reputation: 3052
From here, iterator returned by into_iter()
yields either of the following T
, &T
or &mut T
, depending on the context. In the below code I'm making using std::mem::swap
function which requires &mut
types as arguments. So, why into_iter()
yields T
instead of &mut T
.
fn main() {
let mut first_list = vec![String::from("abcde"), String::from("fghij"), String::from("klmno"), String::from("pqrst"), String::from("uvwxy")];
let second_list: Vec<String> = first_list.into_iter().rev().map(|x| {
let mut d = String::from("");
std::mem::swap(x, &mut d);
d
}).collect::<Vec<String>>();
assert_eq!(vec![String::from("uvwxy"), String::from("pqrst"), String::from("klmno"), String::from("fghij"), String::from("abcde")], second_list);
assert_eq!(vec![0, 0, 0, 0, 0], vec![first_list[0].len(), first_list[1].len(), first_list[2].len(), first_list[3].len(), first_list[4].len()]);
}
I know I can replace into_iter
with iter_mut
to get it compiled successfully. But just want to know the reason behind this.
Error
error[E0308]: mismatched types
--> src/main.rs:5:28
|
5 | std::mem::swap(x, &mut d);
| -------------- ^ expected `&mut String`, found `String`
| |
| arguments to this function are incorrect
|
= note: expected mutable reference `&mut String`
found struct `String`
note: function defined here
--> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:732:14
|
732 | pub const fn swap<T>(x: &mut T, y: &mut T) {
| ^^^^
help: consider mutably borrowing here
|
5 | std::mem::swap(&mut x, &mut d);
| ++++
For more information about this error, try `rustc --explain E0308`.
Upvotes: 0
Views: 25