给定以下代码:
use std::iter::Iterator;
trait Sequence {
type SeqType: Iterator<Item = u32>;
fn seq(&self) -> Option<Self::SeqType>;
}
struct Doubler<'a>(Option<&'a [u32]>);
impl<'a> Sequence for Doubler<'a> {
type SeqType = Box<dyn Iterator<Item = u32>>;
// NOT WORKING
fn seq(&self) -> Option<Self::SeqType> {
self.0
.map(|v| Box::new(v.to_vec().into_iter().map(|x| x * 2)))
}
}
fn print_seq<S: Sequence>(seq: S) {
let v: Option<Vec<u32>> = seq.seq().map(|i| i.collect());
println!("{:?}", v);
}
fn main() {
let v = vec![1, 2, 3, 4];
print_seq(Doubler(Some(&v)));
}
编译器会抱怨:
error[E0308]: mismatched types
--> src/main.rs:16:9
|
15 | fn seq(&self) -> Option<Self::SeqType> {
| --------------------- expected `std::option::Option<std::boxed::Box<(dyn std::iter::Iterator<Item = u32> + 'static)>>` because of return type
16 | / self.0
17 | | .map(|v| Box::new(v.to_vec().into_iter().map(|x| x * 2)))
| |_____________________________________________________________________^ expected trait object `dyn std::iter::Iterator`, found struct `std::iter::Map`
|
= note: expected enum `std::option::Option<std::boxed::Box<(dyn std::iter::Iterator<Item = u32> + 'static)>>`
found enum `std::option::Option<std::boxed::Box<std::iter::Map<std::vec::IntoIter<u32>, [closure@src/main.rs:17:58: 17:67]>>>`
但它通过替换来工作seq
:
fn seq(&self) -> Option<Self::SeqType> {
fn convert(s: &[u32]) -> Box<dyn Iterator<Item = u32>> {
Box::new(s.to_vec().into_iter().map(|x| x * 2))
}
self.0.map(convert)
}
代码可以在这里测试。
唯一的区别是失败示例中使用了闭包,而另一个使用(命名?)函数,但逻辑是相同的。这似乎是一生的问题,但一直无法弄清楚。此外,Option::map
应该急切地消耗价值,然后应该立即使用闭包。
为什么闭包示例失败?