rust - 我不知道为什么我不能使用格式!向量上的内部 for 循环
问题描述
编译器说存在终止生命周期的临时值,但我不知道如何防止这种情况。
fn connectPesel(Names: &mut Vec<&str>){
let mut rng = rand::thread_rng();
for i in 0..Names.len(){
Names[i] = format!("{} {}", Names[i], rng.gen_range(1000..9999)).as_str();
}
}
13 | fn connectPesel(Names: &mut Vec<&str>){
| - let's call the lifetime of this reference `'1`
...
16 | Names[i] = format!("{} {}", Names[i], rng.gen_range(1000..9999)).as_str();
| -----------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| assignment requires that borrow lasts for `'1`
|
解决方案
尝试更改Names
to的类型&mut Vec<String>
,因为调用者需要负责在使用字符串完成后释放内存,而不是立即释放它。(见https://dev.to/stevepryde/rust-string-vs-str-1l93)
推荐阅读
- python - Python Regex - 可选匹配,不捕获一个匹配
- json - 检查 JSON 嵌套属性是否存在
- matlab - 使用 ismember 将嵌套的 for 循环转换为将两个数组的列匹配为 parfor 循环
- nuxt.js - 需要 Sass-loader 和 node-sass(因此 nuxt-sass-resources-loader aswel)作为产品依赖项
- php - 类方法如何在php中返回
- c++ - 如何在 windows 上使用和配置 clang-tidy?
- swift - 获取输出帧失败,状态 8196
- ios - VNRectangleObservation 角在 iPhone 上的 x 轴上压缩
- json - 有没有办法在 Angular6 路由期间延迟加载静态 json?
- scala - 在 Scala 中使用带有类型参数化函数的 jmock