gpt4 book ai didi

loops - 如何为具有基础集合的结构实现非消耗性的IntoIterator?

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

假设我有一个具有集合的struct,例如Vec作为其数据成员之一:

struct MyCollection {
data: Vec<i32>
}

我希望 MyCollection的用户能够遍历其数据,而无需直接访问 Vec本身,如下所示:
let x = MyCollection{data:vec![1, 2, 3, 4, 5]};

for i in &x {
//...
}

但是,我正在努力通过 IntoIterator为非消费版本实现必要的Trait &x。我已经成功实现了消费版本:
impl std::iter::IntoIterator for MyCollection {
type Item = i32;
type IntoIter = std::vec::IntoIter<Self::Item>;

fn into_iter(self) -> Self::IntoIter {
return self.data.into_iter();
}
}

但是,只能按以下方式使用:
for i in x {
println!("{:?}", i);
}

消耗 x。克隆数据是可能的,但是非常昂贵,所以我想避免这种情况。

到目前为止,这是我基于 std::vec::Vecsource implementation的非使用版本的内容:
impl<'a> std::iter::IntoIterator for &'a MyCollection {
type Item = &'a i32;
type IntoIter = std::vec::IntoIter<Self::Item>;

fn into_iter(self) -> Self::IntoIter {
return self.data.into_iter();
}
}

产生以下编译错误:
error: mismatched types
error: expected &i32, found i32
note: expected type `std::vec::IntoIter<&i32>`
found type `std::vec::IntoIter<i32>`
error: expected `std::vec::IntoIter<&i32>` because of return type

我还尝试删除了 &'atype Item,因为在我的情况下, data的元素都具有 Copy的功能,但这产生了以下内容:
error: cannot move out of `self.data` which is behind a shared reference
error: move occurs because `self.data` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait

我知道该函数需要一个矢量的 IntoIter来引用,但是我不确定如何有效地给它一个。我是Rust的新手,所以我非常感谢您对此问题的澄清。如果您还可以告诉我,如何以相同的方式创建一个可变的迭代器以进行写访问,则可以得到加分。

最佳答案

首先,您应该使用切片类型,您的用户不必知道您的内部类型是矢量。然后,您的问题是您不能直接使用IntoIter类型,而必须直接使用Iter类型。

简单的例子:

struct MyCollection {
data: Vec<i32>,
}

impl<'a> std::iter::IntoIterator for &'a MyCollection {
type Item = <std::slice::Iter<'a, i32> as Iterator>::Item;
type IntoIter = std::slice::Iter<'a, i32>;

fn into_iter(self) -> Self::IntoIter {
self.data.as_slice().into_iter()
}
}

fn main() {
let x = MyCollection {
data: vec![1, 2, 3, 4, 5],
};

for i in &x {
println!("{}", i);
}
}

关于loops - 如何为具有基础集合的结构实现非消耗性的IntoIterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59780165/

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