Crates.io | builder-rs |
lib.rs | builder-rs |
version | 0.1.0 |
source | src |
created_at | 2024-03-16 13:46:09.238565 |
updated_at | 2024-03-16 13:46:09.238565 |
description | A procedural macro for generating builder patterns for Rust structs. |
homepage | |
repository | https://github.com/yourlogarithm/builder-rs |
max_upload_size | |
id | 1175641 |
size | 8,031 |
#[derive(Builder)]
struct Foo {
pub a: i32,
pub b: String,
pub c: bool,
pub d: Option<usize>,
}
let foo = Foo::builder()
.a(-3)
.b("Hello, world!".to_string())
.c(true)
.d(Some(2048))
.build();
assert_eq!(-3, foo.a);
assert_eq!("Hello, world!".to_string(), foo.b);
assert_eq!(true, foo.c);
assert_eq!(Some(2048), foo.d);
The macro requires that fields implement the Default
. When a value for the field is not provided it will assign the default value:
#[derive(Builder)]
struct DefaultFoo {
pub a: i32,
pub b: bool,
}
let foo = DefaultFoo::builder()
.build();
assert_eq!(0, foo.a);
assert_eq!(false, foo.b);
Declaring fields that do not implement the Default
trait will result in a compile error:
pub struct NonDefault {}
#[derive(Builder)]
pub struct Foo {
d: NonDefault, // error[E0277]: the trait bound `NonDefault: Default` is not satisfied
}