gpt4 book ai didi

iterator - 如何将实现特征的类型的迭代器的内容装箱?

转载 作者:行者123 更新时间:2023-11-29 08:08:36 25 4
gpt4 key购买 nike

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

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

这有什么不同?我如何表达我想将它们 BoxA,而不是它们可能是什么类型?

最佳答案

您需要转换 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()
}

How is [returning Box::new directly] any different?

作为Sven Marnach points out :

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.

关于iterator - 如何将实现特征的类型的迭代器的内容装箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48180008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com