Skip to content

Instantly share code, notes, and snippets.

@kunalarya
Last active September 30, 2018 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kunalarya/d44a0444f7d21b32c5f51afe3c364612 to your computer and use it in GitHub Desktop.
Save kunalarya/d44a0444f7d21b32c5f51afe3c364612 to your computer and use it in GitHub Desktop.
Mutating struct members in a match arm in Rust

It's sometimes useful to mutate struct members within a match statement: Playground link

struct Foo {
    elms: Option<Vec<u32>>
}

fn main() {
    let mut f = Foo { elms: Some(vec![1, 2, 3]) };
    let replace_with = vec![4, 5, 6];
    replace_elms(&mut f, &replace_with);
    println!("f.elms = {:?}", f.elms);
    // Prints: f.elms = Some([4, 5, 6])
}

fn replace_elms(foo: &mut Foo, with: &Vec<u32>) {
    // There's no need to annotate foo.elms with &mut, as it's
    // already a mutable borrow.
    match foo.elms {
        // Note that we're mutating e here not foo.elms directly
        Some(ref mut e) => *e = with.clone().to_vec(),
        None => ()
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment