Setter

Derive Macro Setter 

Source
#[derive(Setter)]
{
    // Attributes available to this derive:
    #[set]
}
Expand description

A procedural macro that automatically generates setter methods for struct and enum fields.

This macro derives setter methods that allow modification of struct fields with configurable visibility and parameter type conversion options.

§Supported Attributes

  • #[set(pub)] - Generates a public setter
  • #[set(pub(crate))] - Generates a crate-visible setter
  • #[set(pub(super))] - Generates a setter visible to parent module
  • #[set(private)] - Generates a private setter
  • #[set(pub, type(AsRef<str>))] - Generates a setter with custom parameter type conversion
  • #[set(pub, Into)] - Generates a setter using impl Into<T> trait bound
  • #[set(pub, type(AsRef<[u8]>))] - Generates a setter with impl AsRef<[u8]> parameter type

§Parameter Type Conversion

Setters support flexible parameter type conversion through trait bounds:

  • type(AsRef<T>) - Accepts any type implementing AsRef<T> and converts using .as_ref().to_owned()
  • type(Into<T>) - Accepts any type implementing Into<T> and converts using .into()
  • type(CustomTrait<T>) - Accepts any type implementing the specified custom trait bound

§Examples

§Basic Usage

use lombok_macros::*;

#[derive(Setter, Debug, Clone)]
struct BasicStruct {
    #[set(pub)]
    name: String,
    #[set(pub(crate))]
    value: i32,
    #[set(private)]
    secret: String,
}

let mut basic = BasicStruct {
    name: "initial".to_string(),
    value: 0,
    secret: "hidden".to_string(),
};
basic.set_name("updated".to_string());
basic.set_value(42);
assert_eq!(basic.name, "updated");
assert_eq!(basic.value, 42);

§Parameter Type Conversion

use lombok_macros::*;

#[derive(Setter, Debug, Clone)]
struct ConversionStruct {
    #[set(pub, type(AsRef<str>))]
    name: String,
    #[set(pub, type(Into<i32>))]
    value: i32,
    #[set(pub, type(AsRef<[u8]>))]
    data: Vec<u8>,
}

let mut conversion = ConversionStruct {
    name: "initial".to_string(),
    value: 0,
    data: vec![1, 2, 3],
};

conversion.set_name("updated");
assert_eq!(conversion.name, "updated");

conversion.set_value(1u8);
assert_eq!(conversion.value, 1);

conversion.set_data(&[4, 5, 6]);
assert_eq!(conversion.data, vec![4, 5, 6]);

§Tuple Structs

use lombok_macros::*;

#[derive(Setter, Debug, Clone)]
struct TupleStruct(
    #[set(pub)] String,
    #[set(pub)] i32,
);

let mut tuple = TupleStruct("hello".to_string(), 1);
tuple.set_0("world".to_string());
tuple.set_1(100);
assert_eq!(tuple.0, "world");
assert_eq!(tuple.1, 100);