My goal is to combine several items in a vector.
For example, the origin vector has three items: [echo, "echo, aaa"]
, I hope to get a new vector that combine the last two items and get: [echo, "echo aaa"]
.
My approach is to push every normal item on to new vector and whenever I found an item start with quote, I push it into a string to concatenate.
The problem is I cannot push the string to the new vector since the compiler complains that the string does not live long enough.
Here is the code:
fn test(cp_vec_tmp: Vec<&str>) -> Vec<&str> {
let mut multi_string = String::new();
let mut whether_has_quote = false;
let mut cp_vec: Vec<&str> = Vec::new();
for index in 0..cp_vec_tmp.len() {
if cp_vec_tmp[index].starts_with("\"") {
whether_has_quote = true;
multi_string = String::new();
}
if whether_has_quote {
multi_string.push_str(cp_vec_tmp[index]);
} else {
cp_vec.push(cp_vec_tmp[index]);
}
if cp_vec_tmp[index].ends_with("\"") {
whether_has_quote = false;
cp_vec.push(&multi_string);
}
}
return cp_vec;
}
I'm thinking that it is because my string is being created temporarily and will be destroyed when leaving the function, so I have to store the string into some permanent place, but I don't know how...