首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建可变迭代器时出现生存期错误

创建可变迭代器时出现生存期错误
EN

Stack Overflow用户
提问于 2021-07-27 17:49:52
回答 1查看 67关注 0票数 2

当我尝试创建自定义迭代器时,我遇到了一些问题。不可变版本工作得很好,但当复制相同的函数来创建可变版本时,出现了终生错误。这是我的问题的一个简化版本:

代码语言:javascript
复制
struct Test {
    map: HashMap<u32, String>
}

impl Test {
    pub fn iter(&self, start: u32, end: u32) -> impl Iterator<Item = &String> {
        (start..=end).filter_map(move |i| {
            self.map.get(&i)
        })
    }

    pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item = &mut String> {
        (start..=end).filter_map(move |i| {
            self.map.get_mut(&i)
        })
    }
}

iter函数运行良好,但iter_mut函数无法编译,出现以下错误:

代码语言:javascript
复制
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/main.rs:21:22
   |
21 |             self.map.get_mut(&i)
   |                      ^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 20:34...
  --> src/main.rs:20:34
   |
20 |         (start..=end).filter_map(|i| {
   |                                  ^^^
note: ...so that closure can access `self`
  --> src/main.rs:21:13
   |
21 |             self.map.get_mut(&i)
   |             ^^^^^^^^
note: but, the lifetime must be valid for the anonymous lifetime defined on the method body at 19:21...
  --> src/main.rs:19:21
   |
19 |     pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item = &mut String> {
   |                     ^^^^^^^^^
note: ...so that the types are compatible
  --> src/main.rs:19:57
   |
19 |     pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item = &mut String> {
   |                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: expected `std::option::Option<&mut std::string::String>`
              found `std::option::Option<&mut std::string::String>`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-27 18:26:34

正如托德所说,iter_mut上的编译错误可能是由于创建了许多对同一HashMap的可变引用而发生的,但我不确定这一点。你可以这样做:

代码语言:javascript
复制
struct Test {
    map: HashMap<u32, String>
}

impl Test {
    pub fn iter(&self, start: u32, end: u32) -> impl Iterator<Item=&String> {
        self.map
            .iter()
            .filter_map(move |k| {
                if (start..=end).contains(k.0) {
                    Some(k.1)
                } else {
                    None
                }
            })
    }

    pub fn iter_mut(&mut self, start: u32, end: u32) -> impl Iterator<Item=&mut String> {
        self.map
            .iter_mut()
            .filter_map(move |k| {
                if (start..=end).contains(k.0) {
                    Some(k.1)
                } else {
                    None
                }
            })
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68542666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档