Sub topic 7
Associated functions and constructors
This chapter assumes you can define a struct, write an impl block, and run a program with cargo. You should also know the basics of ownership and borrowing.
What an associated function is
An associated function is a function inside an impl block that has no self parameter. It belongs to the type, not to an instance, so you call it with :: and the type name. You have already used one: String::from.
| Kind | First parameter | Call syntax |
|---|---|---|
| Associated function | none, or any non-`self` type | `Rectangle::new(3, 4)` |
| Method | `self`, `&self`, or `&mut self` | `r.area()` |
Constructors by convention
Rust has no constructor keyword. A constructor is an ordinary associated function that returns Self. By convention the main one is called new. Inside an impl block, Self is an alias for the type being implemented. Using it means you don't repeat the type name, and the code stays correct if you rename the struct.
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
fn square(size: u32) -> Self {
Self::new(size, size)
}
fn checked(width: u32, height: u32) -> Option<Self> {
if width == 0 || height == 0 {
None
} else {
Some(Self::new(width, height))
}
}
}
fn main() {
let a = Rectangle::new(3, 4);
let b = Rectangle::square(5);
let c = Rectangle::checked(0, 2);
println!("{:?} {:?} {:?}", a, b, c);
}The code shows three common patterns:
newtakes the fields directly and uses field init shorthand.squareis a named constructor. It gives a second way to build the type and reusesnew.checkedcan fail, so it returnsOption<Self>. UseResult<Self, E>when the caller needs to know why it failed.
That empty fence above is not part of the chapter. The diagram below is the real one.
Why constructors matter
A constructor is the one place where you can enforce rules about a new value. If the fields are private, code outside the module cannot write Rectangle { width: 0, height: 0 }. It has to go through your constructors, so checked can guarantee that no zero-sized rectangle ever exists.
Common mistakes
- Calling an associated function with a dot.
r.new(1, 2)fails becausenewhas noself. - Calling a method with
::and no receiver.Rectangle::area()fails because there is no instance to read. - Writing the type name inside the
implblock everywhere, which makes renaming harder. PreferSelf. - Writing
newwith no arguments whenDefaultfits better. Derive or implementDefault, as the derive chapter shows.
Exercise
You want a Rectangle::from_area_and_width(area, width) constructor that returns None when width is zero or area is not evenly divisible by width. What should its return type be, and does it take self?
Show answer
It returns Option<Self>, because construction can fail and the caller needs to handle the failure. It takes no self, because it is an associated function that creates a new instance. You call it as Rectangle::from_area_and_width(12, 3).