首页 > 解决方案 > 我不知道为什么我不能使用格式!向量上的内部 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`
   |

标签: rust

解决方案


尝试更改Namesto的类型&mut Vec<String>,因为调用者需要负责在使用字符串完成后释放内存,而不是立即释放它。(见https://dev.to/stevepryde/rust-string-vs-str-1l93


推荐阅读