rust - 尝试实现借用一些数据并拥有其他数据的迭代器时出现编译错误

标签 rust

<分区>

我正在尝试实现一个迭代器:

struct MyIterator<'a> {
    s1: &'a str,
    s2: String,

    idx: usize,
}

impl<'a> MyIterator<'a> {
    fn new(s1: &str) -> MyIterator {
        MyIterator {
            s1: s1,
            s2: "Rust".to_string(),

            idx: 0,
        }
    }
}

impl<'a> Iterator for MyIterator<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        self.idx += 1;

        match self.idx {
            1 => Some(self.s1),
            2 => Some(&self.s2),
            _ => None,
        }
    }
}

我收到了这条非常详细的错误消息,但我不知道如何修复代码:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src\main.rs:39:23
   |
39 |             2 => Some(&self.s2),
   |                       ^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 34:5...
  --> src\main.rs:34:5
   |
34 | /     fn next(&mut self) -> Option<Self::Item> {
35 | |         self.idx + 1;
36 | |
37 | |         match self.idx {
...  |
41 | |         }
42 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src\main.rs:39:23
   |
39 |             2 => Some(&self.s2),
   |                       ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 31:1...
  --> src\main.rs:31:1
   |
31 | / impl<'a> Iterator for MyIterator<'a> {
32 | |     type Item = &'a str;
33 | |
34 | |     fn next(&mut self) -> Option<Self::Item> {
...  |
42 | |     }
43 | | }
   | |_^
note: ...so that types are compatible (expected std::iter::Iterator, found std::iter::Iterator)
  --> src\main.rs:34:46
   |
34 |       fn next(&mut self) -> Option<Self::Item> {
   |  ______________________________________________^
35 | |         self.idx + 1;
36 | |
37 | |         match self.idx {
...  |
41 | |         }
42 | |     }

为什么 s2 生命周期不是简单的 'a

最佳答案

返回值的类型为 Option<&'a str> ,但是'a不保留 MyIterator<'a>还活着,所以它可能会超出范围,随之而来的是包含的 s2: String .所以'a根本不保留 s2活。 (它只使 s1 保持事件状态,如果您编写了 fn new(s1: &'a str) -> MyIterator<'a> 会更容易看到)

此外 Iterator trait 的设计方式是您永远 返回对存储在 Iterator 中的内容的引用本身在 next功能。

相反,您可以创建一个存储值的类型并实现 IntoIterator 用于对其的引用(使用包含对存储对象的引用的单独迭代器类型)。

关于rust - 尝试实现借用一些数据并拥有其他数据的迭代器时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054316/

相关文章:

rust - 无法从另一个 crate 导入模块 - Unresolved 导入

rust - 借用亲子关系检查器

loops - 是否可以明确指定循环迭代的生命周期?

rust - 可以在Rust中使用通用类型的特征对象吗?

rust - 从 fmt::Argus 获取数据而不进行堆分配

rust - Tokio 的简单 TCP 回显服务器示例(在 GitHub 和 API 引用上)有什么好的详细解释?

rust - 向单向链表添加追加方法

rust - HashMap 的 split_at_mut 等效吗?

rust - 在调用异步 fns 时创建值流?

rust - 数据待定 : interior mutability or separate HashMap?