rust - 为什么声明的顺序会影响编译是否成功?
问题描述
我写了一个简单的 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 功能还是错误?
解决方案
推荐阅读
- c# - 在 .Net Core 3.1 上使用 Azure AD B2C 获取 OBO 流的错误 AADST50013
- javascript - 尝试从客户端访问 Node/Express 端点时出现 404 Not Found
- java - 在 android Firebase 中看到或未看到消息
- java - 如何让 JButton 在恢复其原始颜色之前更改颜色一段时间
- javascript - v-card 组件 Vuetify 的背景图片未显示
- go - 尝试连接 Redis JSON
- javascript - 当文档不在焦点时如何识别keyup事件
- javascript - 反应代码拆分:import()函数的参数不是字符串
- server - 如何通过代理设置端口转发?
- python - 嵌入矩阵和一个热向量(Pytorch)