#[chainable]Expand description
Convenience macro that generates builder-like chainable methods from setter or adder methods in an
inherent implementation, trait definition, or from fields in a struct
§Examples
§On an inherent method
struct Example {
field_0: bool,
opt_field: Option<usize>
}
impl Example {
fn new() -> Self {
Example {
field_0: false
}
}
#[chainable]
fn set_field_0(&mut self, val: bool) {
self.field_0 = val;
}
// this will make the generated method take usize as an argument
// instead of Option<usize>
#[chainable(collapse_options)]
fn set_opt_field(&mut self, opt_field: Option<usize>) {
self.opt_field = opt_field;
}
}
let example = Example::new().field_0(true);
println!("Value of field_0: {}", example.field_0);§In a trait definition
To use the macro in a trait definition, it must be a subtrait of [Sized]. This macro
will also make a trait object unsafe
pub trait ExampleTrait: Sized {
#[chainable]
fn set_something(&mut self, val: u32);
#[chainable]
fn set_something_else(&mut self, val: u32) {
self.set_something(val);
}
}§In a struct definition
In a struct definition, the specified fields will have chainable methods generated for them with the same visibility as that field
#[derive(Default, Debug)]
#[chainable]
struct Example {
// generated chainable method with documentation
#[chainable(doc = "Documentation for `field_0`")]
field_0: bool,
field_1: usize,
field_2: f64,
// this will make the generated method take usize as an argument
// instead of Option<usize>
#[chainable(collapse_option)]
opt_field: Option<usize>
}
let example = Example::default()
.field_0(false)
.field_1(100)
.field_2(std::f64::consts::PI)
.opt_field(1);
println!("{example:?}");§Method Visibility
Methods generated by this macro have the same visibility as the annotated item
(if the struct field or method is pub, so will the generated methods)
§Options for struct fields:
§collapse_option
If the field is Option<T>, make the generated chainable method take T as its argument
§use_into_impl
Make the generated chainable method take impl Into<T> and convert it to the field’s type
§doc = "Your documentation here"
Creates documentation for the generated chainable method
§Options for setter and adder methods
§collapse_options
If any methods are Option<T>, collapse them to their inner types
§use_into_impl
Make all the methods take Into<T> and convert them to their input types