5 releases (2 stable)

1.1.0 May 30, 2024
1.0.0 Sep 21, 2023
0.3.0 Sep 21, 2023
0.2.0 Sep 20, 2023
0.1.0 Sep 19, 2023

#433 in Procedural macros

Download history 61/week @ 2024-07-14 120/week @ 2024-07-21 247/week @ 2024-07-28 60/week @ 2024-08-04 137/week @ 2024-08-11 74/week @ 2024-08-18 90/week @ 2024-08-25 91/week @ 2024-09-01 123/week @ 2024-09-08 11/week @ 2024-09-15 62/week @ 2024-09-22 24/week @ 2024-09-29 74/week @ 2024-10-06 81/week @ 2024-10-13 2/week @ 2024-10-20 8/week @ 2024-10-27

165 downloads per month

MIT license

9KB
90 lines

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.


lib.rs:

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:

Struct Field Accessor Return Type
String [&str][str]
Primitive T (e.g. [i64]) 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 #[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.

Dependencies

~235–680KB
~16K SLoC