作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个具有集合的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::Vec
的
source 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
&'a
的
type 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/
如何配置storekit在一次交易中购买多于一种产品。 要求:1个信用= 1个产品。 在我的应用程序中,我想给用户购买5个积分的选项。 提前致谢 最佳答案 从iOS文档中找到答案! 我们可以使用SKM
我是一名优秀的程序员,十分优秀!