rust - 如何在不进行分配的情况下从迭代器的下一个方法返回结构体的可变成员?

标签 rust

我有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/

相关文章:

rust - 我可以获取字节数组并将其反序列化为结构吗?

winapi - 为什么从 winapi 复制到我的代码中的结构定义没有相同的行为?

rust - Rust 中的红黑树,得到 'expected struct Node, found mutable reference'

struct - 如何声明一个结构,其中只有一些成员可以使用另一个结构的值?

rust - 如何解构元组以使绑定(bind)可变?

rust - vector.into_iter().filter(some_non_trivial_function).collect() 是否可接受

rust - 将宏参数传递给其他宏

c++ - 不使用指针的递归数据结构

python - Python神经网络代码的Rust实现

rust - 无法在安全的 Rust 中创建循环链表;不安全版本崩溃