rust 如何迭代一个包含引用的向量?

0h4hbjxa  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(136)

下面是我的代码:

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()。我测试了一下,它是有效的。但是我不知道原因。

9o685dep

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只是其中之一)。

相关问题