patternrustTip
impl blocks: attaching methods and associated functions to types
Viewed 0 times
implmethodsselfassociated functionsconstructornewstruct
Problem
Developers from OOP backgrounds are unsure how to define constructors and methods on Rust structs without classes.
Solution
Use impl blocks to define methods (&self, &mut self) and associated functions (no self) like constructors:
#[derive(Debug)]
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
// Associated function — called as Rectangle::new()
pub fn new(width: f64, height: f64) -> Self {
Rectangle { width, height }
}
// Immutable method — borrows self
pub fn area(&self) -> f64 {
self.width * self.height
}
// Mutable method — requires mut binding
pub fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
// Consuming method — takes ownership
pub fn into_square(self) -> Rectangle {
let side = self.width.max(self.height);
Rectangle { width: side, height: side }
}
}
let mut r = Rectangle::new(3.0, 4.0);
println!("Area: {}", r.area());
r.scale(2.0);Why
Rust separates data (struct fields) from behavior (impl blocks). Multiple impl blocks for the same type are allowed and often used to separate trait implementations from inherent methods.
Gotchas
- Self (capital S) is an alias for the implementing type inside an impl block
- You can have multiple impl blocks for the same type — useful for organizing trait impls separately
- Methods taking self by value consume the instance — the caller cannot use it afterward
Revisions (0)
No revisions yet.