0

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...

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Your issue is quite similar to [Return local String as a slice (&str)](https://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str), potentially a duplicate. – E_net4 Aug 25 '17 at 21:54
  • 1
    Your code contains many other issues and smells: you should iterate over the actual elements of a collection, not by index (e.g. `for s in cp_vec_tmp` instead of `for i in 0..cp_vec_tmp.len()`); You don't have to write `return` at the end of the function's body, `cp_vec` is sufficient; And see [why you should avoid taking `Vec<&str>` as a function argument](https://stackoverflow.com/q/40006219/1233251). – E_net4 Aug 25 '17 at 21:57
  • *my string is being created temporarily and will be destroyed when leaving the function* — absolutely correct, nicely reasoned! In Rust, a `String` *is* the "some place" you want to use to hold onto it. You may also be interested in [`Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html). – Shepmaster Aug 25 '17 at 22:01
  • 1
    Perhaps [something like this](https://play.integer32.com/?gist=7983b10625ce507500b73f4773719f36&version=stable). – Shepmaster Aug 25 '17 at 23:10
  • @Shepmaster Thank you ! I'm new to rust so the example you provided is super useful!! – LHY_iS_Learning Aug 25 '17 at 23:31

0 Answers0