Skip to content
Theory · Structs · lesson 5 of 8

Associated functions and new

So far only a literal creates an Order value, and each time it has to list every field. It is handier when the type has its own action "create an order".

Picture a stack of blank slips on the café counter. The action "hand out a new slip" belongs to the kind of slip, not to one filled-in sheet: no filled-in sheet exists yet. Types have such actions too, and you have already met one: String::from("Anna") creates a string even though no string existed before the call.

Rust
struct Order {
    items: u32,
}

impl Order {
    fn new(items: u32) -> Self {
        Self { items }
    }
}

fn main() {
    let order = Order::new(3);
    println!("{}", order.items); // 3
}

Let's walk through the example line by line:

  1. fn new(items: u32) -> Self is declared in the impl block, but without self: it needs no existing order.
  2. Self in the return type stands for the type named in the impl header, that is, Order.
  3. Self { items } is an ordinary struct literal. The field items gets the value of the parameter with the same name, as in the short form of a literal.
  4. Order::new(3) calls the function with ::, and order receives an order with three portions.
  5. println! prints 3.

A function without self

An associated function is a function in an impl block with no self parameter. It belongs to the type itself, not to any one of its values. That is why you call it not with a dot but with the path Type::name: Order::new(3), String::from("Anna").

How it differs from a method:

  • a method's first parameter is self, and you call it on a value: order.total();
  • an associated function has no self, and you call it on the type: Order::new(3).

This is where the stack-of-slips analogy falls short. An associated function does not have to hand out a new slip. It is any function that needs no particular order: it could, for example, return the price of one portion.

new is a convention, not a constructor

In Java or C++ a class has a constructor, a special function the language calls by itself. Rust has no constructors: a value is always created by a struct literal. new is an ordinary associated function that builds that literal, and the name new is chosen by common convention. Call it create and everything works the same, but readers are used to new.

Interviewers like to ask this: "Does Rust have constructors?" The answer:

  • the language has no constructors: a value is always created by a struct literal;
  • new is an ordinary associated function, and its name is a convention, not a keyword;
  • new has no special powers, and a type can have several such functions.

Several ways to create a value

Rust has no overloading: you cannot declare two new functions with different parameters in one type. So each way of creating a value gets its own name. A type can have several impl blocks, and the compiler merges them:

Rust
impl Order {
    fn empty() -> Self {
        Self::new(0)
    }

    fn total(&self) -> u32 {
        self.items * 50
    }
}

let a = Order::new(3);
let b = Order::empty();
println!("{} {}", a.total(), b.total()); // 150 0

Let's go step by step:

  1. The second impl Order block adds two more functions to the type, next to new from the first block.
  2. empty() calls Self::new(0): inside impl you refer to your own type through Self.
  3. Order::new(3) and Order::empty() are two ways to create an order, each with its own name.
  4. The method total works out the total for both, and println! prints 150 0.

Common mistake

An associated function is called with a dot, like a method:

Rust
let a = Order::new(3);
let b = a.empty(); // ✗
println!("{} {}", a.total(), b.total());
TEXT
error[E0599]: no method named `empty` found for struct `Order` in the current scope

The program does not compile. The dot passes the value a into the self parameter, and empty has no such parameter. The compiler explains: this is an associated function, not a method, and suggests the call Order::empty().

Key points

  • An associated function is declared in impl without self and is called with ::: Order::new(3).
  • Self inside impl stands for the type itself: -> Self, Self { items }, Self::new(0).
  • Rust has no constructors: new is an ordinary function named so by convention.
  • There is no overloading, so different ways to create a value get different names.