capypad
0 day streak
rust / intermediate
Snippet

Struct Methods and Associated Functions

Structs in Rust group related data. The impl block contains methods that operate on the struct. The new function is an associated function (constructor), while area and scale are instance methods. scale takes &mut self to modify the struct.

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
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 main() {
let mut r = Rectangle::new(5, 10);
println!("Area: {}", r.area());
r.scale(2);
println!("Scaled area: {}", r.area());
}
Breakdown
1
struct Rectangle {
Defines a struct with two u32 fields
2
impl Rectangle {
Begins implementation block for Rectangle
3
fn new(width: u32, height: u32) -> Self {
Associated function returning a new Rectangle instance
4
fn area(&self) -> u32 {
Method taking immutable reference, returns computed area
5
fn scale(&mut self, factor: u32) {
Method taking mutable reference to modify the struct