2 个版本

0.1.1 2024 年 8 月 25 日
0.1.0 2024 年 8 月 25 日

916开发工具

Download history · Rust 包仓库 186/week @ 2024-08-20 · Rust 包仓库

每月 186 次下载

MIT 许可协议

9KB
65

simple-builder

在 Rust 中轻松生成 builder 模式。

使用方法

use simple_builder::Builder;
#[derive(Default, Builder)]
struct MyBuilder {
    a: i32,
    pub b: i32,
    #[skip]
    c: i32,
}
let builder = MyBuilder::default()
    .a(1)
    .b(2);
assert_eq!(builder.a, 1);
assert_eq!(builder.b, 2);
// c is not settable, so it remains the default value
assert_eq!(builder.c, 0);

lib.rs:

这个包提供了一个 derive-宏,用于为结构体生成 builder 模式。builder 实现包含一个针对结构体每个字段的函数,忽略带有 #[skip] 属性的字段。要为生成函数的字段必须是 Option 类型。如果有任何字段不是 Option 类型,并且没有 #[skip] 属性,宏将引发 panic。

示例

use build_it::Builder;
#[derive(Default, Builder)]
struct MyAwesomeStruct {
    name: Option<String>,
    pub age: Option<u32>,
    #[skip]
    address: String,
    #[skip]
    pub phone: Option<String>,
}
let builder = MyAwesomeStruct::default()
    .name("Alice".to_string())
    .age(42);
    // Note that `address` and `phone` do not have builder methods because of the #[skip]
    // attribute.
assert_eq!(builder.name, Some("Alice".to_string()));
assert_eq!(builder.age, Some(42));

// These fields are skipped, so they're value will still be the default value.
assert_eq!(builder.address, String::default());
assert_eq!(builder.phone, None);

生成的 builder 方法还会显示字段的文档

use build_it::Builder;
#[derive(Default, Builder)]
struct MyAwesomeStruct {
    /// Name of the person
    name: Option<String>,
    /// Age of the person
    age: Option<u32>,
}

这将生成以下 builder 方法

impl MyAwesomeStruct {
   /// Name of the person
    pub fn name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }
    /// Age of the person
    pub fn age(mut self, age: u32) -> Self {
        self.age = Some(age);
        self
    }
}

依赖

~255–700KB
~17K SLoC