1

I wrote a simple Rust program. Depending on the order of my variable declaration, compilation succeeds or fails.

fn main() {
    let my_env: &String;
    let options: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
    my_env = &options[1];
    let _ = my_env;
}
error[E0597]: `options` does not live long enough
 --> src/main.rs:4:15
  |
4 |     my_env = &options[1];
  |               ^^^^^^^ borrowed value does not live long enough
5 |     let _ = my_env;
6 | }
  | - `options` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

When I declare my_env right after the options, the compilation is a success. Is this a Rust feature or a bug?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
the duck
  • 375
  • 3
  • 13
  • 1
    Are stuck on Edition 2015 and unable to use Edition 2018 for some reason? Updating to 2018 will solve this problem because of non-lexical lifetimes. – Peter Hall Apr 03 '19 at 19:55
  • See: https://stackoverflow.com/q/55285018/493729, https://stackoverflow.com/q/50251487/493729 – Peter Hall Apr 03 '19 at 19:59
  • 2
    Any version since 1.31, but you need to enable it in your `Cargo.toml`. See the linked question: https://stackoverflow.com/q/55285018/493729 – Peter Hall Apr 03 '19 at 21:12
  • 1
    @x-ray hope this will help https://stackoverflow.com/questions/55504416/how-do-i-use-a-specific-edition-of-rust/55504418#55504418 – Stargateur Apr 03 '19 at 21:17
  • Thanks everyone, I thought I needed a new version of Rust, but with the edition="2018" in the toml file, it works. – the duck Apr 03 '19 at 22:38

0 Answers0