capypad
0 day streak
rust / intermediate
Snippet

Struct Methods with Impl

impl blocks define methods on structs. &self borrows the struct immutably, &mut self borrows mutably, and no self creates an associated function (constructor). Self refers to the implementing type. New is a convention for constructors, and square demonstrates a static factory method pattern.

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
struct Rectangle {
width: u32,
height: u32,
}
 
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Rectangle { width, height }
}
fn area(&self) -> u32 {
self.width * self.height
}
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
fn square(size: u32) -> Self {
Self { width: size, height: size }
}
}
 
fn main() {
let rect = Rectangle::new(10, 5);
println!("Area: {}", rect.area()); // 50
let sq = Rectangle::square(4);
println!("Square area: {}", sq.area()); // 16
let mut r = Rectangle::new(3, 3);
r.scale(2);
println!("Scaled: {}x{}", r.width, r.height); // 6x6
}
Breakdown
1
impl Rectangle { ... }
Implementation block attaching methods to Rectangle struct
2
fn new(width: u32, height: u32) -> Self
Associated function (constructor) returns new Rectangle instance
3
fn area(&self) -> u32
Method borrowing self immutably, read-only access
4
fn scale(&mut self, factor: u32)
Method borrowing self mutably, allows field modification
5
Self { width, height }
Self alias avoids repeating struct name in constructor