I need a function that gets an Option
of an generic type T
that implements the trait std::iter::IntoIterator
.
A naive implementation could look like the following (yes, the unwrap would panic on None
):
fn main() {
let v = vec![1i32, 2, 3];
print_iter(Some(v));
print_iter(None);
}
fn print_iter<T: IntoIterator<Item = i32>>(v: Option<T>) {
for e in v.unwrap() {
println!("{}", e);
}
}
Test on playground.
This works as expected for Some(...)
, but fails for None
with:
error[E0282]: type annotations needed
--> src/main.rs:4:5
|
4 | print_iter(None);
| ^^^^^^^^^^ cannot infer type for `T`
Obviously the type of T
is unknown in those cases. One could use print_iter::<Vec<i32>>(None);
but this does not feel really idiomatic, because this gives some arbitrary type that isn't based on anything...
Is there any way to hint to the compiler that I don't care for None
or use some kind of default?