Attribute Macro purpurea::accessors[][src]

#[accessors]

Generates accessor methods with names corresponding to those of the the struct’s fields.

Accessors take &self and return a reference to the corresponding field. You can use the accessors attribute with or without providing field names.

For Copy types, you will need to apply dereferencing in order to obtain the value. This is a price for keeping things simple.

Examples

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

mod examples {
    use purpurea::*;

    #[accessors]
    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 city: &str = "Los Angeles";
let street: &str = "Elm street";
let number: u16 = 13;

let new_address = Address::new(city, street, number);

assert_eq!(city, new_address.city());
assert_eq!(street, new_address.street());
assert_eq!(number, *new_address.number());
assert!(!*new_address.verified());

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

mod examples {
    use purpurea::*;
     
    #[accessors(email, is_admin)]
    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 email = "john_doe@example.com";
let john_doe = User::new(email, 45275, true);

assert_eq!(email, john_doe.email());
assert!(*john_doe.is_admin());

Panics

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