如何装入实现特征的类型的迭代器的内容? [英] How can I box the contents of an iterator of a type that implements a trait?

查看:201
本文介绍了如何装入实现特征的类型的迭代器的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用某种类型的迭代器,它必须实现特性 A ,并尝试将其转换为 Vec of Box es的特征:

I'm taking an iterator of some type that must implement the trait A, and trying to convert it into a Vec of Boxes of that trait:

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>>>()
}

然而,这无法编译,说:

However, this fails to compile, saying:

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

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

This error kind of makes sense, but then I don't see why there's no problem with the following:

fn test<'a, T: A + 'a>(t: T) -> Box<A + 'a> {
    Box::new(t)
}

那是怎么回事不同?我怎么表达我想 Box 他们作为 A s,而不是他们可能是什么类型?

How is that any different? How can I express that I'd like to Box them as As, rather than whatever type they may be?

推荐答案

你需要施放 Box< I :: Item> 进入 Box< 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) as Box<A>)
        .collect()
}




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

as Sven Marnach指出


您不需要在函数中进行显式强制转换的原因是块的最后一个语句是强制站点,并且在这些站点上隐式发生强制。有关更多详细信息,请参见关于强制作用的章节

The reason why you don't need an explicit cast in the function is that the last statement of a block is a coercion site and coercions happen implicitly at these sites. See the chapter on coercions in the nomicon for further details.

这篇关于如何装入实现特征的类型的迭代器的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆