18 个版本
0.6.0 | 2023年11月7日 |
---|---|
0.5.9 | 2021年2月8日 |
0.5.8 | 2019年8月18日 |
0.5.7 | 2019年7月11日 |
0.3.0 | 2016年11月19日 |
#32 在 过程宏 中
261,965 每月下载量
在 705 个 Crates 中使用 (直接使用 231 个)
19KB
322 行
为 #[derive(new)]
实现自定义 derive
derive(new)
属性为标注的类型创建一个 new
构造函数。该函数接受类型中每个字段的参数,提供简单的构造函数。这很有用,因为随着类型的演变,你可以使构造函数变得复杂(添加或删除字段),而无需更改客户端代码(即,不破坏向后兼容性)。这也是初始化结构体或枚举的最简洁方式。
实现使用宏 1.1 自定义 derive(从 1.15 开始在稳定 Rust 中工作)。
如果您禁用了默认功能 "std"
,则 #[no_std]
完全受支持。
示例
Cargo.toml
[dependencies]
derive-new = "0.5"
包含宏
-
Rust 版本 2015
#[macro_use] extern crate derive_new;
-
Rust 版本 2018
use derive_new::new;
为简单结构生成构造函数
#[derive(new)]
struct Bar {
a: i32,
b: String,
}
let _ = Bar::new(42, "Hello".to_owned());
默认值可以通过以下方式指定:通过 #[new(default)]
属性,该属性从构造函数中移除参数并使用 Default::default()
填充字段,或者通过 #[new(value = "..")]
初始化字段为给定表达式
#[derive(new)]
struct Foo {
x: bool,
#[new(value = "42")]
y: i32,
#[new(default)]
z: Vec<String>,
}
let _ = Foo::new(true);
支持泛型类型;特别是,PhantomData<T>
字段将不包括在参数列表中,并将自动初始化
use std::marker::PhantomData;
#[derive(new)]
struct Generic<'a, T: Default, P> {
x: &'a str,
y: PhantomData<P>,
#[new(default)]
z: T,
}
let _ = Generic::<i32, u8>::new("Hello");
对于枚举,为每个变体生成一个构造函数,类型名称将被转换为蛇形大小写;否则,所有针对结构体的支持功能也适用于枚举变体
#[derive(new)]
struct Enum {
FirstVariant,
SecondVariant(bool, #[new(default)] u8),
ThirdVariant { x: i32, #[new(value = "vec![1]")] y: Vec<u8> }
}
let _ = Enum::new_first_variant();
let _ = Enum::new_second_variant(true);
let _ = Enum::new_third_variant(42);
依赖关系
~285–740KB
~18K SLoC