在两个单独的向量中创建对 Rust 字符串的引用

Ada*_*dam 3 rust

我有一个输入向量String,我想创建两个包含&str对这些字符串的引用的向量。这是我正在尝试的简化版本(输入被简单的向量初始化替换):

let colours = vec!["red".to_string(), "black".to_string(), "blue".to_string()];
let mut starts_with_b = Vec::new();
let mut ends_with_e = Vec::new();

for colour in colours {
    if colour.starts_with("b") {
        starts_with_b.push(&*colour);
    }
    if colour.ends_with("e") {
        ends_with_e.push(&*colour);
    }
}

println!("{:?}", starts_with_b);
println!("{:?}", ends_with_e);
Run Code Online (Sandbox Code Playgroud)

此代码会产生编译器错误“‘颜色’的寿命不够长”。我该如何解决这个问题?

我发现如果我从字符串引用开始,这个问题就不存在&str

let colours = vec!["red", "black", "blue"];
let mut starts_with_b = Vec::new();
let mut ends_with_e = Vec::new();

for colour in colours {
    if colour.starts_with("b") {
        starts_with_b.push(colour);
    }
    if colour.ends_with("e") {
        ends_with_e.push(colour);
    }
}

println!("{:?}", starts_with_b);
println!("{:?}", ends_with_e);
Run Code Online (Sandbox Code Playgroud)

at5*_*321 5

您的代码的问题来自于临时colour变量是moving 的 String事实,这意味着它的寿命非常短暂。在starts_with_bends_with_e向量中,您需要存储对 中的值的引用,这可以通过在迭代它们时移动值来colours轻松完成。最简单的方法是这样做:colours

for colour in &colours {
Run Code Online (Sandbox Code Playgroud)

而不是这个:

for colour in colours {
Run Code Online (Sandbox Code Playgroud)

这种方式colour的类型将是&String,而不是 (moved) String,因此您可以colour直接直接推送。

请注意,这样 和 的类型starts_with_bends_with_eVec<&String>和 not Vec<&str>,正如您所要求的那样。我认为这对您来说不是问题,但如果是,您可以 Vec<&str>通过简单地调用push(&colour[..])而不是 来轻松制作它们push(colour)