Methods and impl in Rust
Attaching behavior to a struct with an impl block.
struct Counter {
count: u32,
step: u32,
}
impl Counter {
fn new(step: u32) -> Self {
Counter { count: 0, step }
}
fn tick(&mut self) -> u32 {
self.count += self.step;
self.count
}
}
fn main() {
let mut c = Counter::new(5);
c.tick();
println!("{}", c.tick());
}
How it works
Selfnames the type insideimpl.newis a conventional associated constructor.&mut selflets a method mutate the instance.
Keywords and builtins used here
CounterSelffnimplletmainmutnewselfstructticku32
The run, in numbers
- Lines
- 19
- Characters to type
- 261
- Tokens
- 94
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.
Step 1 of 2 in Structs & methods, step 11 of 15 in Ownership & borrowing.