1 个不稳定版本
0.1.0 | 2021年6月4日 |
---|
#2835 在 Rust 模式
6KB
此包导出一个宏 Struct
用于实例化具有共同字段的 struct,用法类似于 struct update 语法,但允许不同类型,并且必须提供字段名称。
用法
let a = Struct! { StructA,
field: value,
...
[field2, field3, ...]: other,
...
};
展开为
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);
宏路径的解决方案
遗憾的是,在宏上下文中,我们无法使用路径(::)来实例化 struct,解决方案是将路径转换为标识符。
用法
The as _Struct
是可选的,_Struct
是默认名称。
let a = Struct! { a_crate::a_mod::StructA as _Struct,
field: value,
...
[field2, field3, ...]: other,
...
};
展开为
let a = {
use a_crate::a_mod::StructA as _Struct;
_Struct {
field: value,
...
field2: other.field2,
field3: other.field3,
...
}
};