使用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;
}
}