Attribute Macro purpurea::mutators [−][src]
#[mutators]
Generates mutator methods with names corresponding to those of the the struct’s fields, with a prefix of set_
.
Mutators take &mut self
and a new value with the type of the corresponding field as arguments, and return &mut Self
so they can be chained.
You can use the mutators attribute with or without providing field names.
Examples
If you don’t provide a list of field names, mutators to all fields are going to be generated by the attribute macro.
mod examples { use purpurea::*; #[mutators] #[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 mut new_address = Address::new("Los Angeles", street, 13); new_address .set_city(new_york.to_owned()) .set_number(sixty_six); assert_eq!(Address::new(new_york, street, sixty_six), new_address);
You can control which fields should have mutators by providing the list of field names (comma-separated if multiple).
mod examples { use purpurea::*; #[mutators(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 mut john_doe = User::new("john_doe@example.com", acct, false); let new_email = "john_doe@example2.com"; john_doe .set_email(new_email.to_owned()) .set_is_admin(true); assert_eq!(User::new(new_email, acct, true), john_doe);
Panics
Panics if it’s applied on tuple structs, enums (and their struct variants), or structs with generics (including lifetime parameters).