Hi,
I recently started learning Rust, and so far I'm really enjoying it. I ran across a situation today which I don't understand, and was hoping somebody with more experience could shed some light on it, since it feels like it could be coming from a fundamental gap in my understanding.
I'm trying to create a vector of references to trait objects. I can implement this like so, and it compiles without a problem:
trait Foo {}
struct Bar {}
impl Foo for Bar {}
fn main() {
let bars = vec![Bar {}];
let mut foos: Vec<&dyn Foo> = vec![];
for bar in bars.iter() {
foos.push(bar);
}
}
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/playground`
However, when I try to create it directly using the collect()
function, it does not compile:
trait Foo {}
struct Bar {}
impl Foo for Bar {}
fn main() {
let bars = vec![Bar {}];
let foos: Vec<&dyn Foo> = bars.iter().collect();
}
Compiling playground v0.0.1 (/playground)
error[E0277]: a value of type `Vec<&dyn Foo>` cannot be built from an iterator over elements of type `&Bar`
--> src/main.rs:10:43
|
10 | let foos: Vec<&dyn Foo> = bars.iter().collect();
| ^^^^^^^ value of type `Vec<&dyn Foo>` cannot be built from `std::iter::Iterator<Item=&Bar>`
|
= help: the trait `FromIterator<&Bar>` is not implemented for `Vec<&dyn Foo>`
= help: the trait `FromIterator<T>` is implemented for `Vec<T>`
note: the method call chain might not have had the expected associated types
--> src/main.rs:10:36
|
8 | let bars = vec![Bar {}];
| ------------ this expression has type `Vec<Bar>`
9 |
10 | let foos: Vec<&dyn Foo> = bars.iter().collect();
| ^^^^^^ `Iterator::Item` is `&Bar` here
note: required by a bound in `collect`
--> /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/iter/traits/iterator.rs:1887:5
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error
Could somebody please explain why a value of type Vec<&dyn Foo>
cannot be built from Iterator<Item=&Bar>
? I'm not sure if I'm missing something small, or fundamentally misunderstanding iterators and/or dynamic dispatch.
Thank you!