#[derive(Assign)]
{
// Attributes available to this derive:
#[debug]
}
Expand description
Derives the Assign 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 Assign 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_assignfeature is active in yourCargo.toml.
§Input Code Example
Given a struct definition annotated with #[ derive( Assign ) ] :
use component_model_types ::Assign;
use component_model_meta ::Assign;
#[ derive( Default, PartialEq, Debug, Assign ) ]
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 component_model_types ::Assign;
use component_model_meta ::Assign;
#[ derive( Default, PartialEq, Debug ) ]
struct Person
{
age: i32,
name: String,
}
impl< IntoT > Assign< i32, IntoT > for Person
where
IntoT: Into< i32 >,
{
fn assign( &mut self, component: IntoT )
{
self.age = component.into();
}
}
impl< IntoT > Assign< 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.