【问题标题】:Extending borrow lifetimes in rust延长生锈的借用寿命
【发布时间】:2014-12-19 17:25:49
【问题描述】:

我正在尝试将一系列解析为令牌树,但是当我尝试实现解析特征时,我收到与引用生命周期相关的错误。我认为创建盒装版本可以解决引用计数或生命周期的任何问题。代码如下。

impl Parse for TokenTree {
    fn parse(&mut self) -> Tree {
        match self.clone() {
            TtDelimited(_, y) => {
                let mut y2 = box (*y).clone();
                match y2.delim {
                    token::DelimToken::Paren => y2.parse(),
                    _ => panic!("not done yet"),
                }
            }
            TtToken(_, t) => E(t),
            _ => panic!("not done yet"),
        }
    }
}

我得到的错误使问题变得清晰,但我找不到有关解决此特定问题的任何信息。

35:51 error: `*y2` does not live long enough
                     token::DelimToken::Paren => y2.parse(),
                                                       ^~
42:6 note: reference must be valid for the anonymous lifetime #1 defined on the block at 30:31...
 fn parse(&mut self) -> Tree{ 
     match self.clone(){
         TtDelimited(_, y) => {
             let mut y2 = box () (*y).clone();
             match y2.delim{
                 token::DelimToken::Paren => y2.parse(),
       ...
 38:14 note: ...but borrowed value is only valid for the block at 32:33
         TtDelimited(_, y) => {
             let mut y2 = box () (*y).clone();
             match y2.delim{
                 token::DelimToken::Paren => y2.parse(),
                 _ => panic!("not done yet"),
             }

【问题讨论】:

    标签: reference rust lifetime


    【解决方案1】:

    在这段代码中:

    {
        let mut y2 = box (*y).clone();
        match y2.delim {
            token::DelimToken::Paren => y2.parse(),
            _ => panic!("not done yet"),
        }
    }
    

    您创建y2,它只会在块退出之前存在。您没有包含您的特征,但我的猜测是 parse 返回对对象本身的引用,例如:

    fn parse(&self) -> &str
    

    引用只能和对象一样长,否则会指向无效数据。

    编辑:它可能如何工作

    您必须跟踪要标记的字符串的生命周期将您的标记生命周期与该输入绑定:

    enum Token<'a> {
      Identifier(&'a str),
      Whitespace(&'a str),
    }
    
    trait Parser {
        // Important! The lifetime of the output is tied to the parameter `input`,
        // *not* to the structure that implements this! 
        fn parse<'a>(&self, input: &'a str) -> Token<'a>;
    }
    
    struct BasicParser;
    
    impl Parser for BasicParser {
        fn parse<'a>(&self, input: &'a str) -> Token<'a> {
            Token::Identifier(input)
        }
    }
    

    【讨论】:

    • 也许吧!如果没有看到更多代码,这很难回答,但我会尝试用一些粗略的草图添加一个编辑。
    猜你喜欢
    • 2014-10-25
    • 2016-06-10
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多