Crate getter_methods
source ·Expand description
getter_methods
is a derive macro that will implement accessor methods for each field on the
struct.
Using getter_methods
is straightforward: simply derive it:
use getter_methods::GetterMethods;
#[derive(GetterMethods)]
struct Foo {
bar: String,
baz: i64,
}
let foo = Foo { bar: "bacon".into(), baz: 42 };
assert_eq!(foo.bar(), "bacon");
assert_eq!(foo.baz(), 42);
§Return types
Accessors will get a convenient return type depending on the type of the field on the struct:
§Returning Copies
If you want a non-primitive T
that implements Copy
to return itself rather than a
reference, annotate it with #[getter_methods(copy)]
:
use getter_methods::GetterMethods;
#[derive(GetterMethods)]
struct Foo {
#[getter_methods(copy)]
bar: Option<i64>,
}
§Skipping fields
If you don’t want a certain field to have an accessor method, annotate it:
ⓘ
use getter_methods::GetterMethods;
#[derive(GetterMethods)]
struct Foo {
bar: String,
#[getter_methods(skip)]
baz: i64,
}
let foo = Foo { bar: "bacon".into(), baz: 42 }
assert_eq!(foo.bar(), "bacon");
assert_eq!(foo.baz(), 42); // Compile error: There is no `foo.baz()`.
§Documentation
Any docstrings used on the fields are copied to the accessor method.
Derive Macros§
- Derive accessor or “getter” methods for each field on the struct.