1 unstable release
0.1.0 | Jun 4, 2021 |
---|
#2397 in Rust patterns
6KB
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:
let a = StructA {
field: value,
...
field2: other.field2,
field3: other.field3,
...
};
Example
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 struct_update::Struct;
let a = Struct! {A,
f1: 3 + 5,
f2: "sss",
[f3, f4]: ..b,
[f5]: ..c,
};
assert_eq!(a.f1, 8);
assert_eq!(a.f2, "sss");
assert_eq!(a.f3, b.f3);
assert_eq!(a.f4, b.f4);
assert_eq!(a.f5, c.f5);
Workaroud for macro path
Pitifully, in macro context we cannot use path(::) to instantiate a struct, the workaround is converting a path to an ident.
Usage
The as _Struct
is optional, _Struct
is the default name.
let a = Struct! { a_crate::a_mod::StructA as _Struct,
field: value,
...
[field2, field3, ...]: other,
...
};
which expand to:
let a = {
use a_crate::a_mod::StructA as _Struct;
_Struct {
field: value,
...
field2: other.field2,
field3: other.field3,
...
}
};