Extending borrow lifetimes in rust

后端 未结 1 1768
野趣味
野趣味 2020-12-22 04:33

I\'m trying to parse a series to tokentrees, but when I try to implement my parsing trait I get an error related to reference lifetimes. I thought creating a boxed version w

相关标签:
1条回答
  • 2020-12-22 05:14

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题