typestar

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

  1. Self names the type inside impl.
  2. new is a conventional associated constructor.
  3. &mut self lets a method mutate the instance.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Structs & methods, step 11 of 15 in Ownership & borrowing.

← Previous Next →