Cloneing but with modification

Is there a idiomatic way to create a updated variant of a struct?

#[derive(Debug, Clone)]
struct State {
    a: u8,
    b: u8,
}

fn main() {
    let s = State { a: 0, b: 1 };
    let s2 = {
        let mut s = s.clone();
        s.a = 2;
        s
    };
    // ^ i would like to see a better way to express the previous block;

    dbg!(s, s2);
}

If the fields you want to keep are Copy then functional update syntax could work for you.

#[derive(Debug, Clone)]
struct State {
    a: u8,
    b: u8,
}

fn main() {
    let s = State { a: 0, b: 1 };
    let s2 = State {
        a: 2,
        ..s
    };

    dbg!(s, s2);
}

If some fields are not Copy, but cloning the whole struct (even the parts you don't need afterwards) isn't too expensive either, you can still explicitly clone

let s2 = State {
    a: 2,
    ..s.clone()
};

unless the struct has any private fields, in which case you cannot use this syntax anymore.

1 Like