Loops 如何为具有基础集合的结构实现非消耗性IntoIterator?
假设我有一个Loops 如何为具有基础集合的结构实现非消耗性IntoIterator?,loops,rust,iterator,iteration,Loops,Rust,Iterator,Iteration,假设我有一个struct,它有一个集合,例如Vec作为其数据成员之一: struct MyCollection { data: Vec<i32> } 然而,对于使用&x的非消费版本,我正在努力实现必要的Trait到迭代器中。我已成功实施了消费版本: impl std::iter::IntoIterator for MyCollection { type Item = i32; type IntoIter = std::vec::IntoIter<Sel
struct
,它有一个集合,例如Vec
作为其数据成员之一:
struct MyCollection {
data: Vec<i32>
}
然而,对于使用&x
的非消费版本,我正在努力实现必要的Trait到迭代器中。我已成功实施了消费版本:
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();
}
}
它消耗x
。克隆数据是可能的,但成本相当高,因此我希望避免这种情况
以下是我到目前为止对非消费版本的介绍,我基于std::vec::vec
:
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();
}
}
我知道函数需要一个向量到引用的插入器,但我不确定如何有效地给它一个。我对生锈还不熟悉,所以我非常希望能澄清这个问题。如果您还可以告诉我如何以相同的方式为写访问创建可变迭代器,则会有额外的好处。首先,您应该使用slice类型,您的用户不必知道您的内部类型是vector。然后,您的问题是不能使用IntoIter
type,而是直接使用Iter
type
简单的例子:
struct MyCollection{
资料来源:Vec,
}
impl;
fn进入iter(self)->self::进入iter{
self.data.as_slice()插入到_iter()中
}
}
fn main(){
设x=MyCollection{
数据:vec![1,2,3,4,5],
};
对于i&x{
println!(“{}”,i);
}
}
首先,您应该使用slice类型,您的用户不必知道您的内部类型是vector。然后,您的问题是不能使用IntoIter
type,而是直接使用Iter
type
简单的例子:
struct MyCollection{
资料来源:Vec,
}
impl;
fn进入iter(self)->self::进入iter{
self.data.as_slice()插入到_iter()中
}
}
fn main(){
设x=MyCollection{
数据:vec![1,2,3,4,5],
};
对于i&x{
println!(“{}”,i);
}
}
“如果您还可以告诉我如何以相同的方式为写访问创建可变迭代器,那么您将获得额外的积分。”哈哈,我将让您将此作为练习,因此“如果您还可以告诉我如何以相同的方式为写访问创建可变迭代器,那么您将获得额外的积分。”哈哈,我将让您以同样的方式进行练习
for i in x {
println!("{:?}", i);
}
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
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