Derive Macro former::ComponentAssign
source · #[derive(ComponentAssign)]
{
// Attributes available to this derive:
#[debug]
}
Expand description
Derives the ComponentAssign
trait for struct fields, allowing each field to be set
with a value that can be converted into the field’s type.
This macro facilitates the automatic implementation of the ComponentAssign
trait for all
fields within a struct, leveraging the power of Rust’s type system to ensure type safety
and conversion logic. It is particularly useful for builder patterns or mutating instances
of data structures in a fluent and ergonomic manner.
§Attributes
debug
: An optional attribute to enable debugging of the trait derivation process.
§Conditions
- This macro is only enabled when the
derive_component_assign
feature is active in yourCargo.toml
.
§Input Code Example
Given a struct definition annotated with #[ derive( ComponentAssign ) ]
:
use former::ComponentAssign;
#[ derive( Default, PartialEq, Debug, former::ComponentAssign ) ]
struct Person
{
age : i32,
name : String,
}
let mut person : Person = Default::default();
person.assign( 13 );
person.assign( "John" );
assert_eq!( person, Person { age : 13, name : "John".to_string() } );
§Generated Code Example
The procedural macro generates the following implementations for Person
:
use former::ComponentAssign;
#[ derive( Default, PartialEq, Debug ) ]
struct Person
{
age : i32,
name : String,
}
impl< IntoT > ComponentAssign< i32, IntoT > for Person
where
IntoT : Into< i32 >,
{
fn assign( &mut self, component : IntoT )
{
self.age = component.into();
}
}
impl< IntoT > ComponentAssign< String, IntoT > for Person
where
IntoT : Into< String >,
{
fn assign( &mut self, component : IntoT )
{
self.name = component.into();
}
}
let mut person : Person = Default::default();
person.assign( 13 );
person.assign( "John" );
assert_eq!( person, Person { age : 13, name : "John".to_string() } );
This allows any type that can be converted into an i32
or String
to be set as
the value of the age
or name
fields of Person
instances, respectively.