#getter-setter #proc-macro #i32

ters

Generate getters and setters procedurally

4 releases

0.2.0 Nov 1, 2025
0.1.3 Nov 1, 2025
0.1.2 Feb 18, 2025
0.1.0 Feb 18, 2025

#505 in Procedural macros

MIT license

5KB
60 lines

Generate getters and setters procedurally.

Annotate fields with #[get] to generate a getter method.

use ters::ters;

#[ters]
struct Foo {
    a: i32,
    #[get]
    b: bool,
}

fn getters() {
    let foo = Foo { a: 42, b: true };
    assert_eq!(foo.b(), &true);
}

Annotate fields with #[set] to generate a setter method.

use ters::ters;

#[ters]
struct Foo {
    #[set]
    a: i32,
    b: bool,
}

fn setters() {
    let mut foo = Foo { a: 42, b: true };
    foo.set_a(31);
}

Annotate fields with #[get] and #[set] to generate both a getter and a setter method.

use ters::ters;

#[ters]
struct Foo {
    #[get]
    #[set]
    a: i32,
    b: bool,
}

fn getters_and_setters() {
    let mut foo = Foo { a: 42, b: true };
    assert_eq!(foo.a(), &42);
    foo.set_a(31);

    assert_eq!(foo.a(), &31);
}

Unannotated fields will not have generated getters or setters.

use ters::ters;

#[ters]
struct Foo {
    a: i32,
    #[get]
    b: bool,
}

fn getters_not_generated() {
    let foo = Foo { a: 42, b: true };
    assert_eq!(foo.a(), &42); // this method doesn't exist
}

Dependencies

~125–500KB
~12K SLoC