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.
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:
fn new(items: u32) -> Selfis declared in theimplblock, but withoutself: it needs no existing order.Selfin the return type stands for the type named in theimplheader, that is,Order.Self { items }is an ordinary struct literal. The fielditemsgets the value of the parameter with the same name, as in the short form of a literal.Order::new(3)calls the function with::, andorderreceives an order with three portions.println!prints3.
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;
newis an ordinary associated function, and its name is a convention, not a keyword;newhas 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:
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 0Let's go step by step:
- The second
impl Orderblock adds two more functions to the type, next tonewfrom the first block. empty()callsSelf::new(0): insideimplyou refer to your own type throughSelf.Order::new(3)andOrder::empty()are two ways to create an order, each with its own name.- The method
totalworks out the total for both, andprintln!prints150 0.
Common mistake
An associated function is called with a dot, like a method:
let a = Order::new(3);
let b = a.empty(); // ✗
println!("{} {}", a.total(), b.total());error[E0599]: no method named `empty` found for struct `Order` in the current scopeThe 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
implwithoutselfand is called with:::Order::new(3). Selfinsideimplstands for the type itself:-> Self,Self { items },Self::new(0).- Rust has no constructors:
newis an ordinary function named so by convention. - There is no overloading, so different ways to create a value get different names.