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



使用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(操场(:

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

操场

#[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;
}
}

最新更新