0

Given this struct:

struct Token<'a> {
     r: &'a Regex,
     f: &'a Fn(String) -> Symbol
}

I can't figure out the right syntax to specify the closure lifetime when returning it from a fn:

fn get_tokens<'a>() -> Vec<Token<'a>> {
    static ref NUMBER: Regex = Regex::new(r"$(\d+|\d*\.\d+)").unwrap(); // TODO avoid "000"?
    let num_token = Token{ r: &*NUMBER, f: &|s| Symbol::Number(s) };
    let tokens = vec![num_token];

    tokens
}

Without a lifetime parameter, I get the error that the borrowed value doesn't life long enough:

error: borrowed value does not live long enough
   --> src\syntax\lex.rs:49:45
   |
49 |     let num_token = Token{ r: &*NUMBER, f: &|s| Symbol::Number(s) };
   |                                             ^^^^^^^^^^^^^^^^^^^^^ temporary value created here
...
53 | }
   | - temporary value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the block at 36:38...
     --> src\syntax\lex.rs:36:39
   |
36 | fn get_tokens<'a>() -> Vec<Token<'a>> {
   |                                       ^

And I can't find any examples that show specifying a lifetime parameter for a closure like this.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Justin Blank
  • 1,768
  • 1
  • 15
  • 32
  • Nothing special about a closure here. You cannot return a reference to a value that was allocated inside a function. – Shepmaster Dec 28 '16 at 03:02
  • You'll likely be interested in http://stackoverflow.com/q/27535289/155423 or http://stackoverflow.com/q/27646925/155423. – Shepmaster Dec 28 '16 at 03:03

0 Answers0