liveBook · Manning

Initializer

As explained in Idiomatic Rust

A constructor is a conventional method or function that creates and returns a newly initialized value of a type.

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

How Idiomatic Rust covers it

How deep it goes
Works through empty and argument-taking struct initializers, then discusses naming and conversion alternatives; does not treat constructors as language machinery.
Examples
Shows `Pizza::new()` creating empty toppings and a revised `new(toppings: Vec<String>)` storing supplied toppings.
What it assumes
Assumes familiarity with Rust structs, `impl` blocks, and vectors while introducing the constructor convention explicitly.
What you can do after
Build it from scratch as a `new` function returning `Self`, or choose `From` for a one-to-one conversion.
How it connects
Connects associated functions and structs to `Vec::new`, the `From` trait, and Rust’s lack of function overloading.

Also explained in

Compare how 9 books explain initializer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.