| Crates.io | derive_builder_apply_to |
| lib.rs | derive_builder_apply_to |
| version | 0.1.0 |
| created_at | 2025-07-27 05:21:20.948966+00 |
| updated_at | 2025-07-27 05:21:20.948966+00 |
| description | A procedural macro for generating apply_to methods for builder patterns |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1769727 |
| size | 8,455 |
A procedural macro for generating apply_to methods for builder patterns, designed to work seamlessly with the derive_builder crate.
The derive_builder crate is fantastic for creating new objects using the builder pattern. However, builders are typically used only for construction - once you call .build(), the builder is consumed.
This crate extends that functionality by allowing you to use builders to modify existing structs. Instead of building new objects, you can selectively update existing ones with only the fields you want to change.
This is especially useful for:
The ApplyTo derive macro generates an apply_to method on builder structs that:
None values)Add this to your Cargo.toml:
[dependencies]
derive_builder = "0.20"
derive-builder-apply-to = "0.1.0"
Then derive both Builder and ApplyTo on your struct:
use derive_builder::Builder;
use derive_builder_apply_to::ApplyTo;
#[derive(Builder, ApplyTo, Default, Debug, PartialEq)]
struct Person {
name: String,
age: u32,
email: Option<String>,
}
fn main() {
// Create an existing person
let mut person = Person {
name: "Alice".to_string(),
age: 30,
email: Some("alice@example.com".to_string()),
};
// Use builder to apply updates directly - no .build() needed!
let changed = PersonBuilder::default()
.age(31)
.email(Some("alice.smith@example.com".to_string()))
.apply_to(&mut person);
assert!(changed);
assert_eq!(person.name, "Alice"); // unchanged
assert_eq!(person.age, 31); // updated
assert_eq!(person.email, Some("alice.smith@example.com".to_string())); // updated
// Applying the same values again returns false
let changed = PersonBuilder::default()
.age(31)
.apply_to(&mut person);
assert!(!changed); // No change since age was already 31
}
The ApplyTo derive macro:
apply_to method on the corresponding builder struct (e.g., PersonBuilder)Option<T> field in the builderSome(value), it compares with the target struct's fieldtrue if any field was changed, false otherwisederive_builder (named fields only)PartialEq for change detectionOption<T> fields for optional updatesLicensed under the MIT License.