This crate export a macro [Struct
] to instantiate a struct with others which have common
fields, the usage is similar to struct update syntax, but allow to different types and must
provide field names.
usage
let a = Struct! { StructA,
field: value,
...
[field2, field3, ...]: other,
...
};
which expand to:
usage
let a = StructA {
field: value,
...
field2: other.field2,
field3: other.field3,
...
};
``` rust struct A { f1: i32, f2: &'static str, f3: i64, f4: &'static str, f5: u64, } struct B { f3: i64, f4: &'static str, } struct C { f5: u64, }
let b = B { f3: 5, f4: "tt" }; let c = C { f5: 7 };
use structupdate::Struct; let a = Struct! {A, f1: 3 + 5, f2: "sss", [f3, f4]: ..b, [f5]: ..c, }; asserteq!(a.f1, 8); asserteq!(a.f2, "sss"); asserteq!(a.f3, b.f3); asserteq!(a.f4, b.f4); asserteq!(a.f5, c.f5); ```
Pitifully, in macro context we cannot use path(::) to instantiate a struct, the workaround is converting a path to an ident.
The as _Struct
is optional, _Struct
is the default name.
usage
let a = Struct! { a_crate::a_mod::StructA as _Struct,
field: value,
...
[field2, field3, ...]: other,
...
};
which expand to:
usage
let a = {
use a_crate::a_mod::StructA as _Struct;
_Struct {
field: value,
...
field2: other.field2,
field3: other.field3,
...
}
};