首页 > 解决方案 > 为什么声明的顺序会影响编译是否成功?

问题描述

我写了一个简单的 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 功能还是错误?

标签: rustborrow-checker

解决方案


推荐阅读