[−][src]Crate derive_getters
Derive Getters
Macro for autogenerating getters. Can only be used on named structs. Will generate getters that will reside in the struct namespace through an impl.
Derives
Only named structs can derive Getters
. Unit structs, unnamed structs, enums and
unions cannot derive Getters
.
Methods generated
The getter methods generated shall bear the same name as the struct fields and be publicly visible. The methods return an immutable reference to the struct field of the same name. If there is already a method defined with that name there'll be a collision.
Usage
Add to your project Cargo.toml;
[dependencies]
derive-getters = "0.0.9"
In lib.rs or main.rs;
use derive_getters::Getters;
Named Structs
use derive_getters::Getters; #[derive(Getters)] struct Number { num: u64, } fn main() { let number = Number { num: 655 }; assert!(number.num() == &655); }
Here, a method called num()
has been created for the Number
struct which gives a
reference to the num
field.
Generic Types
This macro can also derive on structs that have simple generic types. For example;
#[derive(Getters)] struct Generic<T, U> { gen_t: T, gen_u: U, }
The macro can also handle generic types with trait bounds. For example;
#[derive(Getters)] struct Generic<T: Clone, U: Copy> { gen_t: T, gen_u: U, }
The trait bounds can also be declared in a where
clause.
Additionaly, simple lifetimes are OK too;
#[derive(Getters)] struct Annotated<'a, 'b, T> { stuff: &'a T, comp: &'b str, num: u64, }
Cannot Do
Const generics aren't handled by this macro nor are they tested.
Derive Macros
Getters | Derive getters |