Rust has no formal constructor or `new` keyword. An initializer is an ordinary associated function, conventionally named `new`, that takes initialization arguments and returns a newly created value. Unlike a C++ constructor, it is not invoked automatically when a value is created. section 4.3 section 4.1.1
Listing 4.6 Modeling a pizza pie
#[derive(Debug, Clone)]
pub struct Pizza {
toppings: Vec<String>,
}
impl Pizza {
pub fn new() -> Self { #1
Self { toppings: vec![] }
}
}
`Pizza::new()` returns `Self` with an empty toppings vector. A caller can create a value with `let pizza = Pizza::new();`. section 4.3
An initializer can also take the values needed to populate a struct. For example, `new(toppings: Vec<String>) -> Self` can return `Self { toppings }`. There is no rule that `new` must be argument-free, although an empty value or one built from the minimum required arguments is often a useful starting point. section 4.3
Listing 4.7 A better pizza constructor
impl Pizza {
pub fn new(toppings: Vec<String>) -> Self { #1
Self { toppings } #2
}
}
This version accepts a vector of toppings and places it directly in the returned `Pizza`. section 4.3
Choose the signature carefully: Rust does not overload functions, so a type can have only one `new` method. When creation is a one-to-one conversion from another value, consider implementing `From` instead; `String::from(…)` is an example of that approach. The initializer is a convention, not a required gate through which every value must pass. section 4.3








