我有following code :
struct MyIterator<'a> {
data: &'a mut Vec<usize>,
}
impl<'a> Iterator for MyIterator<'a> {
type Item = &'a [usize];
fn next(&mut self) -> Option<Self::Item> {
self.data.push(1); // Mutate the Vec.
Some(&self.data)
}
}
但是出现这个编译错误:
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/lib.rs:10:14
|
10 | Some(&self.data)
| ^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
--> src/lib.rs:8:13
|
8 | fn next(&mut self) -> Option<Self::Item> {
| ^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:10:14
|
10 | Some(&self.data)
| ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
--> src/lib.rs:5:6
|
5 | impl<'a> Iterator for MyIterator<'a> {
| ^^
note: ...so that the types are compatible
--> src/lib.rs:8:46
|
8 | fn next(&mut self) -> Option<Self::Item> {
| ______________________________________________^
9 | | self.data.push(1);
10 | | Some(&self.data)
11 | | }
| |_____^
= note: expected `<MyIterator<'a> as Iterator>`
found `<MyIterator<'_> as Iterator>`
For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error
我可以在克隆我的 data
结构成员时执行以下操作:
struct MyIterator<'a> {
data: &'a mut Vec<usize>,
}
impl<'a> Iterator for MyIterator<'a> {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Self::Item> {
self.data.push(1);
let data = self.data.clone();
Some(data)
}
}
但是不想在每次调用 next 时分配一个新的 Vec
。有没有什么方法可以让我在没有分配的情况下拥有相同的逻辑?
最佳答案
你想做的事不可能以你现有的方式完成。正如 @trentcl 所解释的,当您迭代时,您将返回对数据的引用。然而,这意味着数据是借用的。如果是这样,您就不能继续通过 push
来不断地弄乱数据。
关于rust - 如何在不进行分配的情况下从迭代器的下一个方法返回结构体的可变成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69775991/