我有一个输入的字符串向量,我想创建两个包含引用(&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);
这段代码会产生编译器错误“'colour' does not live long enough”(颜色不够长久)。我该如何解决这个问题?
我发现,如果我使用字符串引用&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);