Programming Languages
Rust
Subjective
Oct 04, 2025
Explain struct methods and associated functions in Rust.
Detailed Explanation
Methods and associated functions:
• Methods take &self, &mut self, or self
• Associated functions don't take self
• Defined in impl blocks
• :: syntax for associated functions
• . syntax for methods
Example:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Associated function (constructor)
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
// Method
fn area(&self) -> u32 {
self.width * self.height
}
}
let rect = Rectangle::new(10, 20);
let area = rect.area();
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts