Extending borrow lifetimes in rust

淺唱寂寞╮ 提交于 2019-11-29 17:19:34

In this code:

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

You create y2, which will only live until the block exits. You didn't include your trait, but my guess is that parse returns a reference to the object itself, something like:

fn parse(&self) -> &str

The reference can only last as long as the object, otherwise it'd point to invalid data.

Edit: How it could maybe, possibly work

You have to track the lifetime of the string you are tokenizing and tie your tokens lifetime to that input:

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)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!