How to iterate over one vector, modify the values and push them to another vector?

Hi,

I have one vector which is immutable and another which is mutable and of different type. I am trying to find a way to modify the values from String to str and append them to mutable vector.
Like this:

let mut args = vec!["a", "b", "c"];
if let Some(additional_args) = optional_args {
     for p in additional_args  {
         args.push("--added");
         args.push(p.clone().as_str());
     }
}

optional_args is of type Option<Vec<String>>.

This gives me an error that temporary value dropped while borrowed.
Is there anyway to clone the value, modify it and push into args?

Assuming the type of optional_args is Option<Vec<String>>, you need to iterate over its references. You can replace the for loop with:

for p in &additional_args {
    args.push("--added");
    args.push(p);
}

Just tried it and now i get the error that additional_args - borrowed value does not live long enough. :sob:

Yeah, I realized afterward that the if let was still transferring ownership. If you do

if let Some(additional_args) = &optional_args {
    for p in additional_args.iter()  {
        args.push("--added");
        args.push(p);
    }
}

then optional_args will still live after the if and you should be OK.

1 Like

Thank you!! IT'S ALIVE! :tada:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.