Search code examples
rustmutable

How can I override all the fields in a mutable reference using another struct?


How can I avoid listing all the fields when using x to populate input?

struct StructX {
    a: u32,
    b: u32,
}

trait TraitY {
    fn foo(info: &mut StructX) -> bool;
}

impl TraitY for SomeZ {
    fn foo(input: &mut StructX) -> bool {
        let mut x = StructX { /*....*/ };
        // do something with x, then finally:
        input.a = x.a;
        input.b = x.b;
    }
}

In C++ it would be just input = x, but that doesn't work in Rust. Note that this is an "interface" so I cannot change the type of input to something else.


Solution

  • You have to dereference input (playground):

    struct StructX {
        a: u32,
        b: u32,
    }
    
    trait TraitY {
        fn foo(info: &mut StructX) -> bool;
    }
    
    impl TraitY for SomeZ {
        fn foo(input: &mut StructX) -> bool {
            let mut x = StructX { /*....*/ };
            // do something with x, then finally:
            *input = x;
    
            return true;
        }
    }
    

    If you wouldn't like to move x into input then you can use Clone::clone_from

    playground

    #[derive(Clone)]
    struct StructX {
        a: u32,
        b: u32,
    }
    
    
    trait TraitY {
        fn foo(info: &mut StructX) -> bool;
    }
    
    struct SomeZ{}
    
    impl TraitY for SomeZ {
        fn foo(input: &mut StructX) -> bool {
            let mut x = StructX { a:42, b:56};
            x.a = 43;
            input.clone_from(&x);
            
            return true;
        }
    }