Derive Macro bagel::Gtor

source · []
    // Attributes available to this derive:
Expand description

Gtor: Get the getters derived

Gtor takes the fields in order and generates getters for each field. For example, if you have fields named userid and name, then the getters generated will be get_userid and get_name, returning references to the appropriate types. In other words, get_* named methods will be derived per your fields.


use bagel::Gtor;
struct MyStruct {
    name: String,
    userid: u64,

let ms = MyStruct { name: "Sayan".to_owned(), userid: 16 };
assert_eq!(ms.get_name(), "Sayan");


The following attributes are available:

  • #[gtor_const]: Will make your gtors constant
  • #[gtor_skip]: Will skip generation of getters for specific fields
  • #[gtor_copy]: Makes the getter return a copy of the value, assuming that the type is Copy
  • #[phantom]: Marks the field as a PhantomData field, hence skipping getters, setters and ctors for the field
  • #[gtor(...)]: See this example

The gtor attribute

Simply add the gtor attribute like this: #[gtor(get, get_mut)] on the top of your struct to get mutable and immutable reference methods to the fields in your struct.


use bagel::{Ctor, Gtor};
#[derive(Ctor, Gtor)]
#[gtor(get, get_mut)]
pub struct Mutable {
    x_axis: u8,
    y_axis: u8,

fn test_get_and_get_mut() {
    let mut m = Mutable::new(0, 0);
    // move x by 1 unit
    *m.get_x_axis_mut() = 1;
    // move y by 2 units
    *m.get_y_axis_mut() = 2;
    assert_eq!(m.get_x_axis(), 1);
    assert_eq!(m.get_y_axis(), 2);

Important notes


If any of the fields within the struct are primitive types that do not require large copies, then the value is returned directly instead of a reference to it:

u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, str, bool, usize, isize, char, f32, f64


The Gtor macro will automatically add a doc comment of the form:

Returns the value for the `<struct_field>` field in struct [`<struct_name>`]