capypad
0 day streak
rust / beginner
Snippet

Associated Functions and Constructor Patterns

Associated functions are methods attached to the type itself rather than an instance. They are defined in impl blocks and often used as constructors (like Rectangle::new). Methods that need to modify the instance take &mut self, while methods that only read data take &self.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
struct Rectangle {
width: u32,
height: u32,
}
 
impl Rectangle {
// Associated function (like a constructor)
fn new(width: u32, height: u32) -> Self {
Rectangle { width, height }
}
// Another associated function for square
fn square(size: u32) -> Self {
Rectangle { width: size, height: size }
}
// Instance method
fn area(&self) -> u32 {
self.width * self.height
}
// Method with mutable reference
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
}
 
fn main() {
let rect = Rectangle::new(30, 50);
let square = Rectangle::square(25);
println!("Rectangle area: {}", rect.area());
println!("Square area: {}", square.area());
let mut scaled_rect = Rectangle::new(10, 10);
scaled_rect.scale(3);
println!("Scaled rectangle: {} x {}", scaled_rect.width, scaled_rect.height);
}
Breakdown
1
fn new(width: u32, height: u32) -> Self
Associated function returning a new Rectangle instance; Self refers to Rectangle
2
fn square(size: u32) -> Self
Alternative constructor for creating a square (equal sides)
3
fn area(&self) -> u32
Method that borrows self immutably to read instance data
4
fn scale(&mut self, factor: u32)
Method that borrows self mutably to modify instance data
5
Rectangle::new(30, 50)
Calling associated function using :: syntax on the type name