4 个稳定版本
1.1.1 | 2020 年 12 月 30 日 |
---|---|
1.1.0 | 2020 年 8 月 8 日 |
1.0.1 | 2020 年 6 月 30 日 |
1.0.0 | 2020 年 6 月 25 日 |
#55 在 无标准库
10,404 每月下载量
用于 51 个 Crates (6 直接)
8KB
89 行
Assign
以声明性风格修改实例!
此模块提供了宏 assign!
以允许以声明性风格修改实例
此宏的动机是使程序员能够以声明性方式编写一系列修改实例字段的操作,作为初始化过程。 assign!
宏还允许程序员跳过定义具有默认值的字段。当依赖项公开一个非穷举的结构时,会使用此类情况。
用法
#[macro_use]
extern crate assign;
fn main() {
struct SomeStruct {
a: u32,
b: Option<f32>,
c: String,
}
impl SomeStruct {
fn new() -> SomeStruct {
SomeStruct {
a: 1u32,
b: None,
c: String::from("old"),
}
}
}
// In order to treat the mutation of field `a` and `c` as an initialization,
// Use assign to mutate field in declarative flavor, thus avoiding the risk inserting code
// between the line that defines a field and the line that defines the other
// Note that field `b` is skipped
let instance = assign!(SomeStruct::new(), {
a: 2u32,
c: String::from("new"),
});
// Equivalent
let instance2 = {
let mut item = SomeStruct::new();
item.a = 2u32;
item.c = String::from("new");
item
};
assert_eq!(instance.a, instance2.a);
assert_eq!(&instance.c, &instance2.c);
assert_eq!(instance.b, instance2.b);
}