如何装入实现特征的类型的迭代器的内容?

时间:2018-01-10 03:47:02

标签: iterator rust boxing

我正在使用某种类型的迭代器,它必须实现特征$str = "Apple (juice)"; for( $i = 0; $i <= strlen( $str ); $i++ ) { if( $str[$i] == '(') $str[$i+1] = strtoupper($str[$i+1]); } echo $str; ,并尝试将其转换为A的{​​{1}}个特征:

Vec

然而,这无法编译,说:

Box

这种错误有道理,但后来我不明白为什么以下内容没有问题:

trait A {}

fn test2<'a, I>(iterator: I) -> Vec<Box<A + 'a>>
where
    I: IntoIterator,
    I::Item: A + 'a,
{
    iterator
        .into_iter()
        .map(|a| Box::new(a))
        .collect::<Vec<Box<A + 'a>>>()
}

这有什么不同?我如何表达我想error[E0277]: the trait bound `std::vec::Vec<std::boxed::Box<A + 'a>>: std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` is not satisfied --> src/main.rs:11:10 | 11 | .collect::<Vec<Box<A + 'a>>>() | ^^^^^^^ a collection of type `std::vec::Vec<std::boxed::Box<A + 'a>>` cannot be built from an iterator over elements of type `std::boxed::Box<<I as std::iter::IntoIterator>::Item>` | = help: the trait `std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` is not implemented for `std::vec::Vec<std::boxed::Box<A + 'a>>` = help: consider adding a `where std::vec::Vec<std::boxed::Box<A + 'a>>: std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` bound fn test<'a, T: A + 'a>(t: T) -> Box<A + 'a> { Box::new(t) } Box,而不是它们可能是什么类型?

1 个答案:

答案 0 :(得分:1)

您需要将Box<I::Item>投射到Box<A>

fn test2<'a, I>(iterator: I) -> Vec<Box<dyn A + 'a>>
where
    I: IntoIterator,
    I::Item: A + 'a,
{
    iterator
        .into_iter()
        .map(|a| Box::new(a) as Box<dyn A>)
        .collect()
}
  

[直接返回Box::new]有何不同?

作为Sven Marnach points out

  

您不需要在函数中进行显式强制转换的原因是块的最后一个语句是强制站点,并且强制在这些站点上隐式发生。有关详细信息,请参阅the chapter on coercions in the nomicon