为什么声明的顺序会影响编译是否成功?

时间:2019-04-03 19:48:26

标签: rust borrow-checker

我写了一个简单的Rust程序。根据变量声明的顺序,编译是成功还是失败。

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

当我在my_env之后声明options时,编译成功。这是Rust功能还是bug?

0 个答案:

没有答案