Crates.io | builder_derive |
lib.rs | builder_derive |
version | 0.0.1 |
source | src |
created_at | 2024-05-05 16:35:49.216979 |
updated_at | 2024-05-05 16:35:49.216979 |
description | A simple proc macro that allows the user to auto generate a simple builder pattern. |
homepage | |
repository | https://github.com/ivario123/builder_derive |
max_upload_size | |
id | 1230342 |
size | 20,008 |
builder-derive provides two main macros, the builder and consumer macro, this crate mainly exists as a support crate for disarmv7 but could be used outside of that. For most cases, there exist better alternatives such as derive_builder
but that one requires unwraps which, in a builder should not be needed as the type system can guarantee safe construction.
use builder_derive::Builder;
#[derive(Builder)]
pub struct CoolStruct {
field_a: usize,
field_b: i32
}
let implementation = CoolStruct::builder().set_field_a(2).set_field_b(4).complete();
assert!(implementation.field_a == 2);
assert!(implementation.field_b == 4);
If any fields are not specified it will fail.
use builder_derive::Builder;
#[derive(Builder)]
pub struct CoolStruct {
field_a: usize,
field_b: i32
}
let implementation = CoolStruct::builder().set_field_a(2).complete();
The consumer pattern is a bit niche but it is useful if you have a bunch of autogenerated structs and want to be certain that you do not miss any cases.
use builder_derive::{Builder,Consumer};
#[derive(Builder,Consumer,PartialEq)]
pub struct CoolStruct {
field_a: usize,
field_b: i32
}
let implementation = CoolStruct::builder().set_field_a(2).set_field_b(4).complete();
assert!(implementation.field_a == 2);
assert!(implementation.field_b == 4);
let consumer = implementation.consumer();
let (field_a,consumer) = consumer.consume_field_a();
let (field_b,consumer) = consumer.consume_field_b();
consumer.consume();
assert!(field_a == 2);
assert!(field_b == 4);
If any fields are not consumed it will fail to compile.
use builder_derive::{Builder,Consumer};
#[derive(Builder,Consumer,PartialEq)]
pub struct CoolStruct {
field_a: usize,
field_b: i32
}
let implementation = CoolStruct::builder().set_field_a(2).set_field_b(4).complete();
assert!(implementation.field_a == 2);
assert!(implementation.field_b == 4);
let consumer = implementation.consumer();
let (field_a,consumer) = consumer.consume_field_a();
consumer.consume();
assert!(field_a == 2);
It would be nice with an extension that allows for generics and an extension that allows the user to specify a conversion function that converts into the field type.
This repository is licensed under the MIT license and any contributions shall be licensed under the same license unless explicitly stated otherwise.