snippetrustModeratepending
Rust struct methods -- impl blocks and trait patterns
Viewed 0 times
implself&self&mut selftraitassociated functionnew
rust
Problem
Need to add methods and associated functions to Rust structs. Understanding self, &self, &mut self, and when to use each.
Solution
Use impl blocks for inherent methods. Implement traits for shared behavior. Choose self receiver based on ownership needs.
Code Snippets
Struct methods with different self receivers
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
// Associated function (no self) -- constructor
fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
// &self: borrow, read-only
fn area(&self) -> f64 {
self.width * self.height
}
// &mut self: mutable borrow
fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
// self: takes ownership (consumes)
fn into_square(self) -> Rectangle {
let side = self.width.max(self.height);
Rectangle::new(side, side)
}
}
// Implement Display trait
impl std::fmt::Display for Rectangle {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}x{}", self.width, self.height)
}
}
let mut r = Rectangle::new(3.0, 4.0);
println!("Area: {}", r.area()); // 12.0
r.scale(2.0);
println!("{}", r); // 6x8Revisions (0)
No revisions yet.