In the following Rust snippet:
fn main() { let list1: Vec<i32> = vec![0, 1, 2, 3, 4]; let it1 = list1.iter(); let tens = it1.map(|x| x * 10).collect::<Vec<i32>>(); println!("{:?}", tens); let it2 = list1.iter(); let doubled_from_iter = scale_it_iter(&it2); println!("{:?}", doubled_from_iter); } fn scale_it_iter(l: &dyn Iterator<Item = &i32>) -> Vec<i32> { l.map(|x| x * 2).collect() } I get this error:
error: the `map` method cannot be invoked on a trait object --> src/main.rs:15:7 | 15 | l.map(|x| x * 2).collect() | ^^^ | ::: /home/xolve/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:625:15 | 625 | Self: Sized, | ----- this has a `Sized` requirement | = note: you need `&mut dyn Iterator<Item = &i32>` instead of `&dyn Iterator<Item = &i32>` error: aborting due to previous error Adding mut as suggested by the compiler solves this. Rust Playground link for working code.
I do not understand why it is needed. It's not needed in main when I call it1.map.
I don't understand the error messages.
the `map` method cannot be invoked on a trait objectis solved by addingmutto the trait reference. This seems contradictory.- How is the message about the
Sizedtrait bound related to the error?
Iterator::mapmutates the iterator, so you need a mutable reference.