首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在结构内容上返回对迭代器的适当的生命周期引用?

如何在结构内容上返回对迭代器的适当的生命周期引用?
EN

Stack Overflow用户
提问于 2018-12-06 17:39:10
回答 2查看 121关注 0票数 2

我正在尝试在一个二维网格上实现一个迭代器,如下所示(这是一个稍微复杂的设置的简化):

代码语言:javascript
复制
struct Grid {
    width: usize,
    height: usize,
}

impl Grid {
    fn new(width: usize, height: usize) -> Grid {
        Grid { width, height }
    }

    fn iter<'a>(&'a self) -> &'a impl Iterator<Item = (usize, usize)> {
        let i = (0..self.height).flat_map(|y: usize| (0..self.width).map(move |x| (x, y)));
        &i
    }
}
代码语言:javascript
复制
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/lib.rs:12:43
   |
12 |         let i = (0..self.height).flat_map(|y: usize| (0..self.width).map(move |x| (x, y)));
   |                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 11:13...
  --> src/lib.rs:11:13
   |
11 |     fn iter<'a>(&'a self) -> &'a impl Iterator<Item = (usize, usize)> {
   |             ^^
   = note: ...so that the types are compatible:
           expected &&Grid
              found &&'a Grid
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that return value is valid for the call
  --> src/lib.rs:11:34
   |
11 |     fn iter<'a>(&'a self) -> &'a impl Iterator<Item = (usize, usize)> {
   |                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我不知道如何向迭代器返回一个适当的生命周期引用。我知道迭代器的生命周期不能超过底层Grid结构的生命周期。

EN

回答 2

Stack Overflow用户

发布于 2018-12-06 18:07:16

返回类型不能是引用。诀窍是为返回类型添加生存期说明符。此外,这两个闭包都需要有move来获取selfy的所有权。

代码语言:javascript
复制
fn iter<'a>(&'a self) -> impl Iterator<Item = (usize, usize)> + 'a {
    (0..self.height).flat_map(move |y| (0..self.width).map(move |x| (x, y)))
}
票数 3
EN

Stack Overflow用户

发布于 2018-12-06 22:34:11

这里没有理由维护对原始结构的任何引用,因为所有的封闭值都实现了Copy。您只需要从结构中提取heightwidth,并在执行此操作时制作一个副本:

代码语言:javascript
复制
fn iter(&self) -> impl Iterator<Item = (usize, usize)> {
    let Self { height, width } = *self;
    (0..height).flat_map(move |y| (0..width).map(move |x| (x, y)))
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53648396

复制
相关文章

相似问题

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