在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。
您必须取消引用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)
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |