如何使用另一个结构覆盖可变引用中的所有字段?

xix*_*xao 1 mutable rust

x用于填充时如何避免列出所有字段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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在 C++ 中它只是input = x,但这在 Rust 中不起作用。请注意,这是一个“接口”,因此我无法将 的类型更改为其他类型input

Max*_*axV 6

您必须取消引用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 = x;

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你不想搬进x去,input那么你可以使用Clone::clone_from

操场

#[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;
    }
}
Run Code Online (Sandbox Code Playgroud)