getset

repository·main·Indexed 18 days ago

https://github.com/jbaublitz/getset

A Rust procedural macro crate (version 0.1.6) that automates the generation of standard getter and setter methods for struct fields to reduce boilerplate. It supports various patterns including reference getters, mutable getters, copy/clone getters, and builder-style setters. Users can control visibility and naming prefixes via struct-level or field-level attributes, and can skip specific fields using the #[getset(skip)] attribute.

Tokens
2.3K
Snippets
7
Records
8
Agent score
14%

What's inside getset

  1. Overview of getset

    main

    getset is a procedural macro crate for Rust that automatically generates basic getters and setters for struct fields. It reduces boilerplate for simple data access patterns where no custom logic is required within the accessors.

    Generated Method Patterns:

    • Getters: fn field(&self) -> &type
    • Setters: fn field(&mut self, val: type) -> &mut Self
    • With Setters: fn with_field(mut self, val: type) -> Self
    • Mutable Getters: fn field_mut(&mut self) -> &mut type
    • Copy Getters: fn field(&self) -> type (for types implementing Copy)
    • Clone Getters: fn field(&self) -> type (for types implementing Clone, useful for Arc)

    Note: Do not use these macros for fields requiring custom logic; implement those manually.

  2. Use getset macros on struct fields

    main

    To use getset, derive the desired trait (e.g., Getters, Setters, MutGetters) on your struct and use the #[getset(...)] attribute on specific fields to control which accessors are generated and their visibility.

    Field-level attributes take precedence over struct-level attributes. You can specify visibility (e.g., pub) directly within the attribute.

    Common attribute options:

    • get: Generates a reference getter.
    • set: Generates a mutable setter returning &mut Self.
    • get_mut: Generates a mutable reference getter.
    • set_with: Generates a with_ style setter returning Self.
    • get_copy: Generates a getter that returns the value by copy.
    • get_clone: Generates a getter that returns the value by cloning (useful for Arc).
    • skip: Prevents generation for a specific field, even if the struct has a general attribute.
    use std::sync::Arc;
    use getset::{Getters, Setters, WithSetters, MutGetters, CopyGetters, CloneGetters};
    
    #[derive(Getters, Setters, WithSetters, MutGetters, CopyGetters, CloneGetters, Default)]
    pub struct Foo<T>
    where
        T: Copy + Clone + Default,
    {
        #[getset(get, set, get_mut, set_with)]
        private: T,
    
        #[getset(get_copy = "pub", set = "pub", get_mut = "pub", set_with = "pub")]
        public: T,
    
        #[getset(get_clone = "pub", set = "pub", get_mut = "pub", set_with = "pub")]
        arc: Arc<u16>,
    }
  3. Configure getter and setter generation with attributes

    main

    You can control how methods are generated using attributes at both the struct and field levels.

    Struct-level Configuration

    Attributes applied to the struct apply to all fields. You can use #[getset(skip)] to prevent a field from having any generated methods.

    Field-level Configuration

    • Visibility: Specify visibility for a specific method: #[getset(get = "pub")].
    • Prefixing: Use with_prefix to add a get_ prefix to the generated method name: #[getset(get = "pub with_prefix")] results in pub fn get_field(&self) -> &T.
    • Skipping: Use #[getset(skip)] to opt-out a field from the macro's generation, allowing you to implement custom logic manually.

    Unary Structs (Tuple Structs)

    For a tuple struct with exactly one field, the macros generate methods named after the macro type (e.g., get(), set(), get_mut()) rather than a field name.

    // Prefixing example
    #[derive(Getters)]
    pub struct Foo {
        #[getset(get = "pub with_prefix")]
        field: bool,
    }
    // Generates: pub fn get_field(&self) -> &bool
    
    // Skipping example
    #[derive(CopyGetters, Setters, WithSetters)]
    #[getset(get_copy, set, set_with)]
    pub struct Foo {
        #[getset(skip)]
        skipped: String,
        field1: usize,
    }
    
    // Unary struct example
    #[derive(Setters, Getters, MutGetters)]
    struct UnaryTuple(#[getset(set, get, get_mut)] i32);
    
    let mut tup = UnaryTuple(42);
    assert_eq!(tup.get(), &42);
  4. Use getset procedural macros to generate getters and setters

    main

    The getset crate provides procedural macros to automatically generate basic getters and setters for struct fields. This reduces boilerplate for simple data access patterns.

    Supported Macro Types

    • Getters: Generates fn field(&self) -> &T.
    • MutGetters: Generates fn field(&mut self) -> &mut T.
    • Setters: Generates fn field(&mut self, val: T) -> &mut Self (builder-style).
    • WithSetters: Generates fn field(mut self, val: T) -> Self (consuming builder-style).
    • CopyGetters: Generates fn field(&self) -> T (requires T: Copy).
    • CloneGetters: Generates fn field(&self) -> T (requires T: Clone, useful for Arc<T>).

    Visibility and Customization

    By default, generated methods use the field's visibility. You can override this using the #[getset(... = "visibility")] syntax (e.g., pub, private).

    Field-level attributes take precedence over struct-level attributes.

    use getset::{Getters, Setters, MutGetters, WithSetters, CopyGetters, CloneGetters};
    
    #[derive(Getters, Setters, MutGetters, WithSetters, CopyGetters, CloneGetters)]
    pub struct Foo {
        #[getset(get = "pub", set = "pub")]
        public_field: i32,
    
        #[getset(get_copy)]
        private_copy_field: u8,
    }
  5. Configure struct-level attributes in getset

    main

    You can apply attributes at the struct level to generate accessors for all fields in that struct. This is useful for applying a default visibility (like pub) to most fields while overriding specific ones at the field level.

    Example: Applying pub to all get_copy methods at the struct level, but keeping one field private.

    #[macro_use]
    extern crate getset;
    
    mod submodule {
        #[derive(Getters, CopyGetters, Default)]
        #[get_copy = "pub"] // By default add a pub getting for all fields.
        pub struct Foo {
            public: i32,
            #[getset(get_copy)] // Override as private
            private: i32,
        }
    }
  6. Skip getter/setter generation for specific fields

    main

    When using struct-level attributes, you can use #[getset(skip)] on a specific field to prevent the macro from generating accessors for it. This is necessary if the field type does not support the requested accessor (e.g., a non-Copy type in a CopyGetters struct) or if you intend to implement the logic manually.

    use getset::{CopyGetters, Setters};
    
    #[derive(CopyGetters, Setters)]
    #[getset(get_copy, set, set_with)]
    pub struct Foo {
        #[getset(skip)]
        skipped: String,
    
        field1: usize,
        field2: usize,
    }
    
    impl Foo {
        // Manual implementation for skipped field
        fn skipped(&self) -> &str {
            &self.skipped
        }
    }
  7. Add a prefix to generated getters

    main

    If you need to maintain compatibility with legacy code or prefer a specific naming convention, you can use the with_prefix option within the get attribute to add a prefix (like get_) to the generated getter methods.

    #[macro_use]
    extern crate getset;
    
    #[derive(Getters, Default)]
    pub struct Foo {
        #[get = "pub with_prefix"]
        field: bool,
    }
    
    fn main() {
        let mut foo = Foo::default();
        let val = foo.get_field();
    }
  8. Reference: getset attribute options

    main

    The following keys are used within the #[getset(...)] attribute to control code generation. These can be used at the struct level (applying to all fields) or the field level (overriding struct settings).

    // Supported keys:
    get
    get_clone
    get_copy
    get_mut
    set
    set_with
    skip
    
    // Supported modifiers/values:
    "pub"
    "private"
    "with_prefix"