Crates.io | struct_update |
lib.rs | struct_update |
version | 0.1.0 |
source | src |
created_at | 2021-06-04 02:13:35.122014 |
updated_at | 2021-06-04 02:13:35.122014 |
description | This crate export a macro to instantiate a struct with others which have common fields |
homepage | |
repository | https://github.com/hhggit/struct_update |
max_upload_size | |
id | 405961 |
size | 8,702 |
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.
let a = Struct! { StructA,
field: value,
...
[field2, field3, ...]: other,
...
};
which expand to:
let a = StructA {
field: value,
...
field2: other.field2,
field3: other.field3,
...
};
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);
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.
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,
...
}
};