Sub topic 7
Associated functions and constructors
This chapter assumes you can define a struct, create instances with field syntax, and write an impl block. You should also know the basics of ownership and borrowing. Here you will learn what associated functions are, how they differ from methods, and how to write constructors that are safe and easy to use.
What an associated function is
An associated function is a function defined inside an impl block that does not take self as its first parameter. It belongs to the type, not to a particular instance. You call it with the path syntax Type::name(...), using a double colon.
You have already used one: String::from("hi"). String::new() and Vec::with_capacity(10) are also associated functions.
The difference from a method is only the first parameter:
| Form | First parameter | Call syntax |
|---|---|---|
| Associated function | none, or anything except a `self` receiver | `Type::f(args)` |
| Method | `self`, `&self`, or `&mut self` | `value.f(args)` |
Methods are also associated functions. You can call a method with path syntax, such as Rectangle::area(&r). The reverse is not true. A function without a self receiver cannot be called with dot syntax.
Constructors by convention
Rust has no constructor keyword. A constructor is an ordinary associated function that returns an instance of the type. The usual name is new, but new has no special meaning to the compiler.
#[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 main() {
let a = Rectangle::new(3, 4);
let b = Rectangle::square(5);
println!("{:?} {:?}", a, b);
}Three details are worth noting:
Selfis an alias for the type named in theimplheader. Insideimpl Rectangle,SelfmeansRectangle. If you rename the struct, the bodies do not need to change.Self { width, height }uses field init shorthand. When a parameter has the same name as a field, you can write the name once.squarecallsSelf::new. Constructors can build on each other, so the logic that sets up an instance lives in one place.
A struct can have several constructors. Because Rust has no function overloading, each one needs a different name. Pick names that say what is different about the input.
Naming conventions
The standard library uses a consistent set of names. Following them makes your API predictable.
| Name | Typical meaning |
|---|---|
| `new` | The main constructor, usually with the most common arguments |
| `with_*` | Construct with one specific setting, such as `Vec::with_capacity` |
| `from_*` | Construct by converting from another representation, such as `String::from_utf8` |
| `default` | Construct with default values, from the `Default` trait |
Constructors that can fail
A constructor is the best place to enforce rules about what a valid value looks like. If invalid input is possible, do not panic by default. Return a Result or an Option and let the caller decide what to do.
#[derive(Debug)]
struct Percentage {
value: u8,
}
#[derive(Debug)]
enum PercentageError {
OutOfRange(u8),
}
impl Percentage {
fn new(value: u8) -> Result<Self, PercentageError> {
if value > 100 {
Err(PercentageError::OutOfRange(value))
} else {
Ok(Self { value })
}
}
fn get(&self) -> u8 {
self.value
}
}
fn main() {
match Percentage::new(85) {
Ok(p) => println!("ok: {}", p.get()),
Err(e) => println!("error: {:?}", e),
}
match Percentage::new(140) {
Ok(p) => println!("ok: {}", p.get()),
Err(e) => println!("error: {:?}", e),
}
}This only protects you if outside code cannot build a Percentage directly. Within the same module, anyone can write Percentage { value: 140 }. The chapter on privacy covers how placing the struct in its own module and keeping the field private closes that gap. For now, treat a validating constructor as the first half of the guarantee.
Constructors and the Default trait
When a type has a sensible zero or empty value, implement or derive Default instead of writing a new that takes no arguments. Generic code and struct update syntax can then use it.
#[derive(Debug, Default)]
struct Settings {
name: String,
retries: u32,
verbose: bool,
}
impl Settings {
fn named(name: &str) -> Self {
Self {
name: name.to_string(),
..Default::default()
}
}
}
fn main() {
let a = Settings::default();
let b = Settings::named("batch");
println!("{:?}", a);
println!("{:?}", b);
}Deriving Default sets every field to its own default: 0 for numbers, false for bool, and an empty String. If those values are wrong for your type, write the implementation by hand.
struct Connection {
port: u16,
timeout_secs: u32,
}
impl Default for Connection {
fn default() -> Self {
Self {
port: 8080,
timeout_secs: 30,
}
}
}
fn main() {
let c = Connection::default();
println!("{} {}", c.port, c.timeout_secs);
}A common convention is that new() with no arguments and Default::default() return the same value. Clippy warns when a public new() takes no arguments and the type has no Default implementation.
Parameter types: borrow or own?
A constructor stores its arguments in fields, so the parameter type decides who pays for allocation. Consider a struct that owns a String.
- Taking
Stringmeans the caller passes ownership. A caller who already holds aStringpays nothing. A caller with a&strmust call.to_string()first. - Taking
&strand calling.to_string()inside is convenient for literals, but a caller who already has an ownedStringpays for a second allocation. - Taking
impl Into<String>accepts both cases and converts only when needed.
#[derive(Debug)]
struct User {
name: String,
}
impl User {
fn new(name: impl Into<String>) -> Self {
Self { name: name.into() }
}
}
fn main() {
let owned = String::from("Grace");
let a = User::new("Ada");
let b = User::new(owned);
println!("{:?} {:?}", a, b);
}The cost is that the function is generic, so the compiler generates one copy for each argument type used. For a small constructor this is fine. For a simple internal type, plain &str or String is easier to read.
Associated constants and non-constructor functions
Associated functions are not only constructors. Any function that relates to the type but needs no instance can live here, such as a parser or a helper. You can also define associated constants in an impl block.
struct Circle {
radius: f64,
}
impl Circle {
const UNIT_RADIUS: f64 = 1.0;
fn unit() -> Self {
Self { radius: Self::UNIT_RADIUS }
}
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
fn main() {
let c = Circle::unit();
println!("{:.3}", c.area());
}Common errors
- Calling an associated function with dot syntax.
r.new(1, 2)fails with an error that says no method namednewwas found. WriteRectangle::new(1, 2). - Forgetting the type path. Writing
new(1, 2)fails with "cannot find functionnewin this scope". An associated function is not in scope by its bare name. - Returning the wrong type. A constructor declared
-> Selfmust return aSelf. If you meant to return aResult, writeResult<Self, E>. - Using
Selfoutside animplblock.Selfonly exists insideimpland trait definitions. - Moving a borrowed value. A constructor that takes
name: &strand tries to store it in aStringfield without converting fails to compile with a type mismatch. Use.to_string(),String::from, or.into().
How it fits together
Exercises
Exercise
What is the difference between an associated function and a method, and how does each get called?
Show answer
A method has a self, &self, or &mut self receiver as its first parameter and is called with dot syntax, such as value.area(). An associated function has no such receiver and is called with path syntax, such as Rectangle::new(3, 4). Methods are also associated functions, so they can be called with path syntax too, but a function without a receiver cannot be called with dot syntax.
Exercise
Write a constructor Temperature::new(celsius: f64) that returns Result<Temperature, String> and rejects values below -273.15. Why does it matter whether the field is private?
Show answer
impl Temperature { fn new(celsius: f64) -> Result<Self, String> { if celsius < -273.15 { Err(format!("{celsius} is below absolute zero")) } else { Ok(Self { celsius }) } } }. If the field is public, or the struct is built in the same module, other code can write Temperature { celsius: -500.0 } and skip the check. Keeping the field private in a separate module forces every instance through new.