简体   繁体   English

实现迭代器的代理方法,生命周期冲突

[英]Proxy method for implementing Iterator, conflicting lifetime

I'm trying to implement an iterator which simply proxies the next method to another method on the struct itself. 我正在尝试实现一个迭代器,该迭代器将struct本身的next方法简单地代理为另一个方法。

struct Element<'a>(&'a str);

struct IterStruct<'a> {
    name: &'a str,
}

impl<'a> IterStruct<'a> {
    fn name(&mut self) -> Option<Element> {
        Some(Element(self.name))
    }
}

impl<'a> Iterator for IterStruct<'a> {
    type Item = Element<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        self.name()
    }
}

I'm getting the conflicting requirements for lifetime error though: 我遇到了终身错误的相互矛盾的要求:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/lib.rs:16:14
   |
16 |         self.name()
   |              ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 15:5...
  --> src/lib.rs:15:5
   |
15 | /     fn next(&mut self) -> Option<Self::Item> {
16 | |         self.name()
17 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:16:9
   |
16 |         self.name()
   |         ^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 13:6...
  --> src/lib.rs:13:6
   |
13 | impl<'a> Iterator for IterStruct<'a> {
   |      ^^
   = note: ...so that the types are compatible:
           expected std::iter::Iterator
              found std::iter::Iterator

Playground 操场

How can I resolve this? 我该如何解决?

One solution is to specify that name outlives the IterStruct it is contained in: 一种解决方案是指定该name超过包含在其中的IterStruct

struct Element<'a>(&'a str);

struct IterStruct<'a> {
    name: &'a str,
}

impl<'a> IterStruct<'a> {
    fn name<'s>(&'s mut self) -> Option<Element<'a>>
    where
        'a: 's, // <- specify that name outlives self
    {
        Some(Element(self.name))
    }
}

impl<'a> Iterator for IterStruct<'a> {
    type Item = Element<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        self.name()
    }
}

Well you need to give borrow checker a way to infer the lifetimes. 那么,您需要给借阅检查器一种推断寿命的方法。 What's essentially missing is one of the following line 基本上缺少的是以下行之一

impl<'a> IterStruct<'a> {
    fn name(&mut self) -> Option<Element> {
//  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        Some(Element(self.name))
    }
}

into fn name(&mut self) -> Option<Element<'a>> . fn name(&mut self) -> Option<Element<'a>> The Rust borrow checker will take care of the rest [Playground link] . Rust借阅检查器将负责其余的工作[Playground link]

Compiler seems smart enough to infer 'a should outlive 'self . 编译器似乎足够聪明,可以推断'a应该活得更长寿'self

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM