capypad
0 day streak
rust / beginner
Snippet

Methods and impl Blocks

Rust uses impl blocks to attach methods to structs. The new function is a common pattern for constructors — it returns Self (the struct type being defined). Methods automatically receive &self (immutable reference) or &mut self (mutable reference) as their first parameter, giving access to the struct's fields. The dot syntax calls methods just like in object-oriented languages.

snippet.rs
rust
1
struct Rectangle {\n width: u32,\n height: u32,\n}\n\nimpl Rectangle {\n fn new(width: u32, height: u32) -> Self {\n Rectangle { width, height }\n }\n \n fn area(&self) -> u32 {\n self.width * self.height\n }\n \n fn can_hold(&self, other: &Rectangle) -> bool {\n self.width > other.width && self.height > other.height\n }\n}\n\nfn main() {\n let rect = Rectangle::new(30, 50);\n println!("Area: {} square pixels", rect.area());\n}
Breakdown
1
impl Rectangle {
Starts an impl block for the Rectangle struct
2
fn new(width: u32, height: u32) -> Self {
Associated function (constructor) returning a new Rectangle instance
3
fn area(&self) -> u32 {
Method taking immutable reference to the struct instance
4
self.width * self.height
Accesses fields directly within a method using self
5
Rectangle::new(30, 50)
Calls the associated function using the type name, not an instance
6
rect.area()
Calls the method on the instance using dot notation