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

问题描述 投票:1回答:1

我正在采用某种类型的迭代器,必须实现特征A,并尝试将其转换为VecBoxes的特征:

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作为As,而不是它们可能是什么类型?

iterator rust boxing
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.