奇怪的是,在下面的代码片段中,第二个函数编译,而不是第三个函数。
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我们应该如何在第三个函数中指定Box::<_>::new来使其编译,以及为什么?
发布于 2022-04-04 04:48:32
在第一个和第二个版本中,您调用的函数不是<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
}https://stackoverflow.com/questions/71731994
复制相似问题