Attribute Macro purpurea::default_constructor[][src]

#[default_constructor]

Generates a constructor method called new.

For field types T, the corresponding constructor argument type will be T. For String fields, the argument type will be &str.

The order of arguments will be the same as in the definition of the struct.

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

Examples

If you don’t provide a list of field names, the constructor will require the values for all fields as arguments.

use purpurea::*;
   
#[default_constructor]
#[derive(Debug, Eq, PartialEq)]
pub struct User {
    email: String,
    account_number: usize,
    bonus_points: Option<u64>
}

let email = "john_doe@example.com";
let account_number = 45275;
let bonus_points = None;
let john_doe = User::new(email, account_number, bonus_points);
let john_doe2 = User { email: email.to_owned(), account_number, bonus_points };

assert_eq!(john_doe, john_doe2);

You can control the arguments the constructor should take by providing the list of field names (comma-separated if multiple).

Fields omitted are going to use the default value of the corresponding type, provided by the Default trait. If the type does not implement Default, the macro will fail.

use purpurea::*;    

#[default_constructor(city, street, number)]
#[derive(Debug, Eq, PartialEq)]
pub struct Address {
    city: String,
    street: String,
    number: u16,
    verified: bool,
    coordinates: Option<Vec<u16>>
}

let city = "Los Angeles";
let street = "Elm street";
let number = 13;
let verified = false;
let new_address = Address::new(city, street, number);
let new_address2 =
    Address {
        city: city.to_owned(),
        street: street.to_owned(),
        number,
        verified,
        coordinates: None
    };

assert_eq!(new_address, new_address2);

Panics

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

Also panics when a field’s type should implement Default but it doesn’t.