Expand description
This crate provides Arraygen
derive macro for structs, which generates methods returning arrays filled with the selected struct fields.
Complete example:
use arraygen::Arraygen;
#[derive(Arraygen, Debug)]
#[gen_array(fn get_names: &mut String)]
struct Person {
#[in_array(get_names)]
first_name: String,
#[in_array(get_names)]
last_name: String,
}
let mut person = Person {
first_name: "Ada".into(),
last_name: "Lovelace".into()
};
for name in person.get_names() {
*name = name.to_lowercase();
}
assert_eq!(
format!("{:?}", person),
"Person { first_name: \"ada\", last_name: \"lovelace\" }"
);
As you can see above, the attribute gen_array
generates a new method returning an array of the given type.
And then, the attribute in_array
indicates the fields to be included by that method. In this case, the
generated method ‘get_names’ will return an array including references to all the fields of the struct.
As you might have guessed, what Arraygen
does under the hood is simply generating the following impl:
impl Person {
#[inline(always)]
fn get_names(&mut self) -> [&mut String; 2] {
[&mut self.first_name, &mut self.last_name]
}
}
Derive Macros§
- Arraygen
- The
Arraygen
derive allows you to use the attributegen_array
at the struct level, and the attributein_array
in each contained field.