Modifying nested vectors within a function

I am struggling to write a function that takes a vector of vectors, and modifies the inner vectors in place.

My non-compiling function - I've removed my previous failed efforts at trying to make the right things mutable, as they were not helping - hopefully the wrong code makes simple what I'm trying to do.

pub fn test_vec(V : Vec<Vec<char>>) {
    let from_vec = V.get(0).unwrap();
    let to_vec = V.get(1).unwrap();
    let ch = from_vec.pop().unwrap();
    to_vec.push(ch);
}

Very grateful for any ideas - it has me stumped!
Thanks,
Wes

Everything you want to mutate, you have to make mutable. Also, you must ensure no overlapping mutable references. Simplifying the unwrapped .get(_mut) calls to indexing syntax and changing the parameter to a reference (to be useful) gives:

pub fn test_vec(v: &mut Vec<Vec<char>>) {
    let ch = v[0].pop().unwrap();
    v[1].push(ch);
}
4 Likes

Thank you! That makes things a lot simpler...!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.