Rust的生命周期:返回指针

时间:2018-11-17 22:59:47

标签: rust

当我编写这样的函数时,

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),
    }
}

我收到此错误:

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

我以为我对锈的寿命有了很好的了解,但显然没有。除了返回String之外,我还有什么选择?

0 个答案:

没有答案