Expand description
This crate provides GettersByType derive macro for structs, which implements a getter method for each type they contain.
The generated methods start with the prefix get_fields_ and end with a transcription of the type they refer.
Example using GettersByType :
use getters_by_type::GettersByType;
#[derive(GettersByType)]
struct Foo {
first: i32,
second: i32,
third: i32,
}
let object = Foo { first: 6, second: 12, third: 24 };
// Let's sum all the i32 fields with a fold expression:
assert_eq!(object.get_fields_i32().iter().fold(0, |acc, x| **x + acc), 42);As you notice, the getter methods return an array containing references to all the fields of the same type.
In that example, the return type of the method get_fields_i32 would be [&i32; 3].
This crate also provides a mut version GettersMutByType which also adds a mut version for those methods.
In this case, the generated methods start with the prefix get_mut_fields_ instead.
Example using GettersMutByType :
use getters_by_type::GettersMutByType;
#[derive(Default)]
struct Updater {}
impl Updater {
fn update(&mut self) {/*...*/}
}
#[derive(GettersMutByType, Default)]
struct Foo {
first: Updater,
second: Updater,
/*...*/
onehundredth: Updater,
}
let mut object = Foo::default();
// Let's update all the Updater fields
for updater in object.get_mut_fields_updater().iter_mut() {
updater.update();
}In this example, the return type of the method get_mut_fields_updater would be [&mut Updater; 3].
There is no dynamic memory allocation happening within the getter methods, as they just return a fixed array with references.
There isn’t also unsafe code being generated.
For more documentation and examples, see each respective documentation section.
Derive Macros§
- Getters
ByType - The
GettersByTypemacro automatically generates animplfor the given struct, implementing a getter method for each different type contained within the struct. - Getters
MutBy Type - The
GettersMutByTypemacro automatically generates animplfor the given struct, implementing a getter method for each different type contained within the struct.