Attribute Macro purpurea::updaters[][src]

#[updaters]

Generates updater methods with names corresponding to those of the the struct’s fields, with a prefix of with_. You won’t have to declare your values mutable.

Updaters take self and a new value with the type of the corresponding field as arguments, and return Self so they can be chained.

You can use the updaters attribute with or without providing field names.

Examples

If you don’t provide a list of field names, updaters to all fields are going to be generated by the attribute macro.

mod examples {
    use purpurea::*;

    #[updaters]
    #[derive(Debug, Eq, PartialEq)]
    pub struct Address {
        city: String,
        street: String,
        number: u16,
        verified: bool
    }

    impl Address {
        pub fn new(city: &str, street: &str, number: u16) -> Self {
            Self {
                city: city.to_owned(),
                street: street.to_owned(),
                number,
                verified: false
            }
        }
    }
}

use examples::*;

let new_york = "New York";
let street = "Elm street";
let sixty_six = 66;

let new_address = Address::new("Los Angeles", street, 13);
let new_address_updated = new_address
    .with_city(new_york.to_owned())
    .with_number(sixty_six);

assert_eq!(Address::new(new_york, street, sixty_six), new_address_updated);

You can control which fields should have updaters by providing the list of field names (comma-separated if multiple).

mod examples {
    use purpurea::*;
     
    #[updaters(email, is_admin)]
    #[derive(Debug, Eq, PartialEq)]
    pub struct User {
        email: String,
        account_number: usize,
        is_admin: bool
    }

    impl User {
        pub fn new(email: &str, account_number: usize, is_admin: bool) -> Self {
            Self {
                email: email.to_owned(),
                account_number,
                is_admin
            }
        }
    }
     
}
use examples::*;

let acct = 45275;
let john_doe = User::new("john_doe@example.com", acct, false);
let new_email = "john_doe@example2.com";
let john_doe2 = john_doe
    .with_email(new_email.to_owned())
    .with_is_admin(true);

assert_eq!(User::new(new_email, acct, true), john_doe2);

Panics

Panics if it’s applied on tuple structs, enums (and their struct variants), or structs with generics (including lifetime parameters).