I found a similar discussion here, but in my case it's about the return type.
I'm trying to return impl Iterator<Item = Box<dyn Iterator<Item = i32>>> from a function. What am I doing wrong to make f2 compile?
Hmm, looks like explicit coercion is needed to give the compiler an extra hint that it can and needs to coerce Box<Once<{integer}>> to Box<dyn Iterator<Item = i32>>:
use std::iter::once;
// This works..
fn f1() -> Box<dyn Iterator<Item = i32>> {
Box::new(once(1))
}
// This doesn't compile
fn f2() -> impl Iterator<Item = Box<dyn Iterator<Item = i32>>> {
once(Box::new(once(1)) as _)
}
I guess you can use the _ placeholder here, because the compiler can infer the type it should coerce to from your function signature's return type. It just needs a nudge to do the coercion, because of the added indirection from the outer call to once. The topic I linked was me struggling to do trait object coercion with collections, which boils down to the same behaviour of Rust's type inference that you experienced with your problem here, I'd say.