迭代器通过引用返回项目,终身问题 [英] Iterator returning items by reference, lifetime issue

查看:110
本文介绍了迭代器通过引用返回项目,终身问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生命周期问题,我正在尝试实现一个迭代器,通过引用返回它的项目,这里是代码:

I have a lifetime issue, I'm trying to implement an iterator returning its items by reference, here is the code:

struct Foo {
   d: [u8; 42],
   pos: usize
}

impl<'a> Iterator<&'a u8> for Foo {
   fn next<'a>(&'a mut self) -> Option<&'a u8> {
      let r = self.d.get(self.pos);
      if r.is_some() {
         self.pos += 1;
      }
      r
   }
}

fn main() {
   let mut x = Foo {
      d: [1; 42],
      pos: 0
   };

   for i in x {
      println!("{}", i);
   }
}

但是这段代码编译不正确,我得到了与参数的生命周期相关的问题,这里是相应的错误:

However this code doesn't compile properly, I get an issue related to the lifetime of parameters, here is the corresponding error:

$ rustc test.rs
test.rs:8:5: 14:6 error: method `next` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime parameter
test.rs:8     fn next<'a>(&'a mut self) -> Option<&'a u8> {
test.rs:9         let r = self.d.get(self.pos);
test.rs:10         if r.is_some() {
test.rs:11             self.pos += 1;
test.rs:12         }
test.rs:13         r
           ...
test.rs:8:49: 14:6 note: expected concrete lifetime is the lifetime 'a as defined on the block at 8:48
test.rs:8     fn next<'a>(&'a mut self) -> Option<&'a u8> {
test.rs:9         let r = self.d.get(self.pos);
test.rs:10         if r.is_some() {
test.rs:11             self.pos += 1;
test.rs:12         }
test.rs:13         r
           ...
error: aborting due to previous error

有人知道如何解决这个问题并仍然通过引用返回项目吗?

Does somebody has an idea how to fix this issue and still returning items by reference?

At至少这个消息意味着什么:预期具体生命周期,但找到绑定生命周期参数

At least what does this message means: expected concrete lifetime, but found bound lifetime parameter ?

推荐答案


关于使用的Rust版本的注意事项:在撰写此问题和答案时, Iterator trait使用了泛型;它已更改为使用关联类型,现在已定义:

Note on the version of Rust used: at the time this question and answer were written, the Iterator trait used generics; it has changed to use associated types and is now defined thus:

pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
    …
}

所以这里显示的错误实现就像这样:

And so the incorrect implementation shown here would be like this:

impl<'a> Iterator for Foo {
    type Item = &'a u8;

    fn next<'a>(&'a mut self) -> Option<&'a u8>;
}

实际上这没有任何影响;只是 A 变为 Self :: Item

In practical terms this affects nothing; it is merely that A becomes Self::Item.

Iterator 特征的定义是:

pub trait Iterator<A> {
    fn next(&mut self) -> Option<A>;
    …
}

请注意: fn next (& mut self) - >选项< A>

这是你拥有的:

impl<'a> Iterator<&'a u8> for Foo {
    fn next<'a>(&'a mut self) -> Option<&'a u8>;
}

请注意: fn next<'a>( &'a mut self) - >选项<&'a u8>

这里有几个问题:


  1. 您已经引入了一个新的通用参数<'a> ,它不应该存在。为了方便起见并强调这里发生的事情,我将配置在impl块ρ0和'a 'a $ c>在方法ρ1上定义。 它们不一样。

  1. You have introduced a new generic parameter <'a> which should not be there. For convenience’s sake and to emphasise what has happened here, I shall dub the 'a defined on the impl block ρ₀ and the 'a defined on the method ρ₁. They are not the same.

& mut self 与特质不同。

返回类型的生命周期与特征不同:其中 A &'ρ0u8 ,返回类型用于 A &'ρ¹u8 。它期望混凝土寿命ρ0,但发现寿命ρ1。 (我不确定正是绑定位意味着什么,所以我会保持安静,以免我错了。)

The lifetime of the return type is different to the trait: where A is &'ρ₀ u8, the return type uses in the place of A &'ρ₁ u8. It expected the concrete lifetime ρ₀ but found instead the lifetime ρ₁. (I’m not certain precisely what the "bound" bit means, so I’ll keep quiet on it lest I be wrong.)

以下是这相当于:您无法将正在迭代的对象的生命周期连接到& mut self 。相反,它必须绑定到您正在实现特征的类型中的某些内容。举一个例子,通过创建连接到基础切片的新迭代器对象来迭代切片中的项目, impl<'a,T>迭代器<&'t>对于项目<'a,T> 。换句话说,迭代特征的设计方式不是,如果你要产生引用,你可以在 self 中返回一些内容,而是返回另一个对象中的内容您有一个引用。

Here’s what this amounts to: you cannot connect the lifetime of the object you are iterating over to &mut self. Instead, it must be bound to something in the type you are implementing the trait for. To take an example, iterating over items in a slice is done by creating a new iterator object connected to the base slice, impl<'a, T> Iterator<&'a T> for Items<'a, T>. Expressed in another way, the way the iteration traits are designed is not, if you are producing references, for you to return something inside self, but rather to return something inside another object that you have a reference to.

对于您的特定的,可能是简单的示例,您应该停止产生引用,或者更改它以使您的迭代器对象不包含数据你正在迭代它只是包含一个引用,例如&'a [T] 甚至类似项目<'a,T>

For your specific, presumably simple example, you should either stop yielding references, or alter it so that your iterator object does not contain the data that you are iterating over—let it merely contain a reference to it, e.g. &'a [T] or even something like Items<'a, T>.

这篇关于迭代器通过引用返回项目,终身问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆