derive-builder-apply-to
A procedural macro for generating apply_to methods for builder patterns, designed to work seamlessly with the derive_builder crate.
Overview
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:
- Partial updates in APIs (PATCH operations)
- Configuration merging
- Applying user preferences to default settings
- Any scenario where you want to modify only specific fields
The ApplyTo derive macro generates an apply_to method on builder structs that:
- Applies only the fields that have been explicitly set (non-
Nonevalues) - Returns a boolean indicating whether any changes were made
- Avoids unnecessary writes when values haven't changed
Usage
Add this to your Cargo.toml:
[]
= "0.20"
= "0.1.0"
Then derive both Builder and ApplyTo on your struct:
use Builder;
use ApplyTo;
How it works
The ApplyTo derive macro:
- Inspects your struct's fields
- Generates an
apply_tomethod on the corresponding builder struct (e.g.,PersonBuilder) - The method iterates through each
Option<T>field in the builder - For each
Some(value), it compares with the target struct's field - Updates the target field only if the value is different
- Returns
trueif any field was changed,falseotherwise
Requirements
- Your struct must work with
derive_builder(named fields only) - Field types must implement
PartialEqfor change detection - The builder struct must have
Option<T>fields for optional updates
License
Licensed under the MIT License.