I have a vector of input Strings and I'd like to create two vectors containing references, &str, to those strings. Here's a simplified version of what I'm trying (the input is replaced with a simple vector initialisation):
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);
This code produces the compiler error "'colour' does not live long enough". How can I resolve this problem?
I've seen that this problem does not exist if I start off with string references, &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);