微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何返回对迭代器中字段的引用?

如何解决如何返回对迭代器中字段的引用?

我需要在由 Iterator 方法返回的结构中保存对 next 字段的引用。然而,编译器无法为借用表达式推断合适的生命周期。 这在 Rust 的当前版本中是否可行,我该怎么做?

以下是简化的代码片段和完整的错误消息:

use std::collections::HashMap;

struct CellDataRef<'a> {
    value: &'a str,}

struct Row<'a> {
    data_ref: &'a HashMap<String,CellDataRef<'a>>,}

struct TableIterator<'a> {
    data: HashMap<String,}

impl<'a> Iterator for TableIterator<'a> {
    type Item = Row<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(Row {
            data_ref: &self.data,})
    }
}

编译器错误

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/lib.rs:20:23
   |
20 |             data_ref: &self.data,|                       ^^^^^^^^^^
   |
note: first,the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
  --> src/lib.rs:18:5
   |
18 |     fn next(&mut self) -> Option<Self::Item> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:20:23
   |
20 |             data_ref: &self.data,|                       ^^^^^^^^^^
note: but,the lifetime must be valid for the lifetime `'a` as defined on the impl at 15:6...
  --> src/lib.rs:15:6
   |
15 | impl<'a> Iterator for TableIterator<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/lib.rs:18:46
   |
18 |       fn next(&mut self) -> Option<Self::Item> {
   |  ______________________________________________^
19 | |         Some(Row {
20 | |             data_ref: &self.data,21 | |         })
22 | |     }
   | |_____^
   = note: expected `Iterator`
              found `Iterator`

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。