10 releases (stable)

Uses new Rust 2024

new 2.0.2 Jun 18, 2025
2.0.1 Jun 9, 2025
1.2.0 May 30, 2025
1.1.0 May 30, 2024
0.1.0 Sep 19, 2023

#493 in Procedural macros

Download history 166/week @ 2025-02-27 67/week @ 2025-03-06 103/week @ 2025-03-13 143/week @ 2025-03-20 35/week @ 2025-03-27 109/week @ 2025-04-03 40/week @ 2025-04-10 56/week @ 2025-04-17 143/week @ 2025-04-24 169/week @ 2025-05-01 36/week @ 2025-05-08 117/week @ 2025-05-15 26/week @ 2025-05-22 398/week @ 2025-05-29 117/week @ 2025-06-05 131/week @ 2025-06-12

683 downloads per month

MIT license

13KB
171 lines

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::Getters;

#[derive(Getters)]
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:

Struct Field Accessor Return Type
Primitive T (e.g. [i64]) T
String [&str][str]
[Vec<T>][Vec] &[T]
[Box<T>][Box] &T
[Option<T>][Option] Option<&T>
Rc<T> Rc<T>
Arc<T> Arc<T>
Any &'a T &'a T
Any *T *T
Any other T &T

Returning Copies

If you want a non-primitive T that implements Copy to return itself rather than a reference, annotate it with #[getters(copy)]:

use getter_methods::Getters;

#[derive(Getters)]
struct Foo {
  #[getters(copy)]
  bar: Option<i64>,
}

Skipping fields

If you don't want a certain field to have an accessor method, annotate it:

use getter_methods::Getters;

#[derive(Getters)]
struct Foo {
  bar: String,
  #[getters(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.


getter-methods

ci docs license

This is getter-methods, a derive macro that will generate an impl with 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);

For more, see the documentation.

Dependencies

~180–600KB
~14K SLoC