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

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

如何避免在使用 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;
    }
}

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

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

如果您不想将 x 移动到 input,那么您可以使用 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;
    }
}