0

When I write a function like this,

fn must_get_env<'a>(key: &'a str) -> &'a str {
    match std::env::var(key) {
        Ok(val) => {
            return &val;
        }
        Err(_) => panic!("Missing required environment variable: {}", key),
    }
}

I get this error:

error[E0597]: `val` does not live long enough
  --> src/main.rs:19:21
   |
19 |             return &val;
   |                     ^^^ borrowed value does not live long enough
...
22 |     }
   |     - borrowed value only lives until here

I thought I had a good understanding of lifetimes in rust, but apparently not. What options do I have besides returning a String?

Gattster
  • 4,613
  • 5
  • 27
  • 39
  • 2
    Why do you not want to return a `String`? – trent Nov 17 '18 at 23:29
  • 1
    `std::env::var(key)` creates `String` so that `String` gets deallocated when you leave the function unless you return it. you cannot return a reference to it. – belst Nov 17 '18 at 23:29
  • tl;dr: you can turn it into a `Box`, `Vec`, etc. but those are all somewhat silly responses. Returning a `String` is the most reasonable thing to do, unless you are doing something *very* unusual. – trent Nov 17 '18 at 23:59
  • Thanks, trentcl and belst. Rust is new to me, but it's starting to make more and more sense. Your comments helped. – Gattster Nov 20 '18 at 19:26

0 Answers0