Rust Tutorial: Methods and impl in Rust
Add methods to structs with impl blocks.
Concepts in this chapter
You will learn and practice:
- **impl** — impl Struct { fn method(&self) -> T }
- **&self** — immutable reference to the struct
- **&mut self** — mutable reference
- **Associated functions** — fn new() -> Self (no self); called with Struct::new()
- **Multiple impl** — you can have several impl blocks for the same type
---
Methods
```rust
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Self {
Counter { count: 0 }
}
fn increment(&mut self) {
self.count += 1;
}
fn get(&self) -> u32 {
self.count
}
}
fn main() {
let mut c = Counter::new();
c.increment();
c.increment();
println!("{}", c.get());
}
```
---
What's Next?
Next: **Traits** — shared behavior and polymorphism.
What you'll learn in this Rust methods and impl in rust tutorial
This interactive Rust tutorial has 2 hands-on exercises. Estimated time: 12 minutes.
- impl and Method — Define a struct Counter with count: u32 (start 0). Add an impl with increment(&mut self) that adds 1 and get(&self) that…
- Associated Function — Add an associated function double_area that takes a side: u32 and returns side * side * 2. From main, print Counter::dou…
Rust Methods and impl in Rust concepts covered
- Concepts in this chapter
- Methods
- What's Next?