简体   繁体   English

Rust 参考寿命应超过 function

[英]Rust Lifetime of reference should outlive function

I have a little dummy parser, which uses the same &str during parsing:我有一个小虚拟解析器,它在解析过程中使用相同的 &str:

struct Parser<'a>{
    r: &'a str,
    pos: usize
}

impl<'a, 'b: 'a> Parser<'a>{
    fn new(s: &'b str)->Parser<'a>{
        Parser{r: s, pos:0}
    }
    fn next(&'a self)->Parser<'a>{
        Parser{r: self.r, pos: self.pos + 1}
    }
    fn nnext(&'a self)->Parser<'a>{
        Parser{r: self.r, pos: self.pos + 2}
    }
    fn nnnext(&'a self)->Parser<'a>{
        return self.next().nnext()
    }
}

I would use it like this:我会这样使用它:

fn parse(s: &str){
    let parser = Parser::new(s);
    parser.nnnext();
}

I get the following error:我收到以下错误:

25 |         return self.next().nnext()
   |                -----------^^^^^^^^
   |                |
   |                returns a value referencing data owned by the current function
   |                temporary value created here

The reference is guaranteed to outlive all Parser methods.保证该引用比所有 Parser 方法的寿命都长。 How must is annotate lifetimes to express this?必须如何注释生命周期来表达这一点? Especially, why does nnnext not compile?特别是,为什么nnnext不编译? It should be clear that the reference outlives self.next().nnext() call.应该清楚的是,引用self.next().nnext()调用更有效。

Thank you very much for any assistance.非常感谢您提供的任何帮助。 Hendrik亨德里克

By using &'a self , you're conflating the lifetime of the parser with the lifetime of the string it refers to.通过使用&'a self ,您将解析器的生命周期与它所引用的字符串的生命周期混为一谈。 There's no reason for that.没有理由这样做。

If you remove this constraint, there's no problem anymore:如果您删除此约束,则不再有问题:

struct Parser<'a>{
    r: &'a str,
    pos: usize
}

impl<'a, 'b: 'a> Parser<'a>{
    fn new(s: &'b str)->Parser<'a>{
        Parser{r: s, pos:0}
    }
    fn next(&self)->Parser<'a>{
        Parser{r: self.r, pos: self.pos + 1}
    }
    fn nnext(&self)->Parser<'a>{
        Parser{r: self.r, pos: self.pos + 2}
    }
    fn nnnext(&self)->Parser<'a>{
        return self.next().nnext()
    }
}

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

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