我需要一个获取实现trait Option的泛型类型的函数。一个幼稚的实现可能看起来像以下内容(是的,解包可能会引起恐慌):Tstd::iter::IntoIteratorNone
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在操场上测试。
这可以按预期工作Some(...),但因以下原因而失败None:
error[E0282]: type annotations needed
--> src/main.rs:4:5
|
4 | print_iter(None);
| ^^^^^^^^^^ cannot infer type for `T`
Run Code Online (Sandbox Code Playgroud)
T在这些情况下,显然类型是未知的。一个人可以使用,print_iter::<Vec<i32>>(None);但这并不是真正的习惯,因为这提供了一些不基于任何东西的任意类型...
有什么方法可以向编译器暗示我不在乎None或使用某种默认值吗?