下面是我的代码:
fn find_rects<'a >(
rects: & Vec<&'a Rectangle>, // reference of a vec containing Rectangle references
width_limit: u32)
-> Vec<&'a Rectangle> // returns a vec of Rectangle references
{
rects
.iter()
.filter(|x| x.width > width_limit)
.collect()
}
它无法编译。错误消息显示:
.collect()
^^^^^^^ value of type `Vec<&Rectangle>` cannot be built from `std::iter::Iterator<Item=&&Rectangle>`
我找到了一个答案,用.copied().collect()
代替.collect()
。我测试了一下,它是有效的。但是我不知道原因。
1条答案
按热度按时间9o685dep1#
如果
my_vec: Vec<T>
,那么my_vec.iter()
是&T
上的迭代器。但是在这种情况下,T
是&Rectangle
,所以迭代器是&&Rectangle
上的迭代器,&&Rectangle
是与&Rectangle
不同的类型,所以不能将x1m7 n1艾德为Vec<&Rectangle>
。iterator.copied()
取得&U
上的迭代器,并通过复制(在Copy
的意义上)每个元素(通过解引用它;copied()
等效于iterator.map(|&x| x)
和iterator.map(|x| *x)
)。剩下的工作就是识别
U
是&Rectangle
,以及&U: Copy
对于任何U
,包括当U
是&Rectangle
时,Iterator<Item=&&Rectangle>::copied()
产生&Rectangle
的迭代器,它实际上可以被collect
转换成Vec<&Rectangle>
(实际上,也可以是任何FromIterator
,其中Vec
只是其中之一)。