我有一个输入向量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)
您的代码的问题来自于临时colour
变量是moving 的 String
事实,这意味着它的寿命非常短暂。在starts_with_b
和ends_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_b
将ends_with_e
是Vec<&String>
和 not Vec<&str>
,正如您所要求的那样。我认为这对您来说不是问题,但如果是,您可以 Vec<&str>
通过简单地调用push(&colour[..])
而不是 来轻松制作它们push(colour)
。