奇怪的是,在下面的代码片段中,第二个函数可以编译,但第三个函数不能编译。
pub fn foo1(iter: Box<dyn Iterator<Item = u8>> ) -> Box<dyn Iterator<Item = u8>> {
Box::new(iter.map(|n| n + 1))
} // This compiles
pub fn foo2(iter: Box<dyn Iterator<Item = u8>> ) -> Box<dyn Iterator<Item = u8>> {
let a: Box::<dyn Iterator<Item = u8>> = Box::<_>::new(iter.map(|n| n + 1));
a
} // This also compiles
pub fn foo3(iter: Box<dyn Iterator<Item = u8>> ) -> Box<dyn Iterator<Item = u8>> {
let a: Box::<dyn Iterator<Item = u8>> = Box::<dyn Iterator<Item = u8>>::new(iter.map(|n| n + 1));
a
} // This does not compile
Run Code Online (Sandbox Code Playgroud)
我们应该如何Box::<_>::new在第三个函数中指定它才能编译,为什么?
在第一个和第二个版本中,您调用的函数不是 <Box<dyn Iterator<Item = u8>>>::new(). 该函数需要T: Sized, 但是dyn Iterator: !Sized. 相反,您调用<Box<SomeConcreteType>>::new(),并将结果强制为Box<dyn Iterator<Item = u8>>。
完全类型指定的版本是:
pub fn foo3(iter: Box<dyn Iterator<Item = u8>>) -> Box<dyn Iterator<Item = u8>> {
let a: Box<dyn Iterator<Item = u8>> = Box::<
std::iter::Map<
Box<dyn Iterator<Item = u8>>, // The original iterator type
_, // The callback type (cannot be named using stable Rust)
>,
>::new(iter.map(|n| n + 1))
as Box<dyn Iterator<Item = u8>>;
a
}
Run Code Online (Sandbox Code Playgroud)