Associated Functions
In this page:
impl Name {
fn new(param: Type) -> Self {
Self { field: param }
}
}
let value = Name::new(arg);
Defining an Associated Function
An associated function lives inside an impl block just like a method, but does not take self, meaning it is not called on an existing instance.
Example: Defining an Associated Function
// Define a struct `Point` to group related fields together
struct Point {
x: i32,
y: i32,
}
// Implement methods on `Point`
impl Point {
// Define the function `origin` with no parameters and returning a `Point`
fn origin() -> Point {
Point { x: 0, y: 0 }
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `p`, set to `Point::origin()`
let p = Point::origin();
// Print "({}, {})" to the console, substituting in `p.x, p.y` (with a trailing newline)
println!("({}, {})", p.x, p.y);
}
Login to try C/C++/Java/PHP code in the editor
The new Convention
By strong community convention, a struct's primary constructor-like associated function is named new, even though Rust has no special built-in new keyword.
Example: The new Convention
// Define a struct `Rectangle` to group related fields together
struct Rectangle {
width: f64,
height: f64,
}
// Implement methods on `Rectangle`
impl Rectangle {
// Define the function `new` taking `width`, `height` and returning a `Rectangle`
fn new(width: f64, height: f64) -> Rectangle {
Rectangle { width, height }
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `rect`, set to `Rectangle::new(4.0, 5.0)`
let rect = Rectangle::new(4.0, 5.0);
// Print "{} x {}" to the console, substituting in `rect.width, rect.height` (with a trailing newline)
println!("{} x {}", rect.width, rect.height);
}
Login to try C/C++/Java/PHP code in the editor
Calling with Type::function() Syntax
Because associated functions have no self, they are called using the type name and double colon, Type::function_name(), rather than dot syntax on an instance.
Example: Calling with Type::function() Syntax
// Define a struct `Square` to group related fields together
struct Square {
side: f64,
}
// Implement methods on `Square`
impl Square {
// Define the function `unit` with no parameters and returning a `Square`
fn unit() -> Square {
Square { side: 1.0 }
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `sq`, set to `Square::unit()`
let sq = Square::unit();
// Print "Unit square side: {}" to the console, substituting in `sq.side` (with a trailing newline)
println!("Unit square side: {}", sq.side);
}
Login to try C/C++/Java/PHP code in the editor
Multiple Associated Constructors
A struct can define several different associated functions that each construct an instance in a different way, giving callers convenient, clearly-named alternatives.
Example: Multiple Associated Constructors
// Define a struct `Color` to group related fields together
struct Color {
r: u8,
g: u8,
b: u8,
}
// Implement methods on `Color`
impl Color {
// Define the function `black` with no parameters and returning a `Color`
fn black() -> Color {
Color { r: 0, g: 0, b: 0 }
}
// Define the function `white` with no parameters and returning a `Color`
fn white() -> Color {
Color { r: 255, g: 255, b: 255 }
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `bg`, set to `Color::white()`
let bg = Color::white();
// Print "Background: ({}, {}, {})" to the console, substituting in `bg.r, bg.g, bg.b` (with a trailing newline)
println!("Background: ({}, {}, {})", bg.r, bg.g, bg.b);
}
Login to try C/C++/Java/PHP code in the editor
- Trying to call an associated function with dot syntax like
instance.new()instead of the correctType::new()syntax. - Forgetting that associated functions do not take
selfat all, unlike regular methods. - Not following the community convention of naming a struct's simple constructor function
new.
- An associated function is defined inside an
implblock but does not takeselfas a parameter. - Associated functions are called using
Type::function_name()syntax, not dot syntax. - The convention
new()is used for a struct's primary constructor-like associated function, though it is not a special keyword. - Associated functions are often used as constructors that return a new instance of the struct.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: