liveBook · Manning

Impl block

As explained in Refactoring to Rust

An impl block is a Rust construct that defines methods and associated functions for a type.

An impl block defines methods and associated functions for a Rust type. Separating these definitions from the type declaration keeps behavior flexible and organized. section 3.2.3

Distinguish functions inside an impl block by their self parameter:

  • Methods operate on an instance and take self, &self, or &mut self. section 3.2.3
  • Associated functions do not take self and resemble static methods or class methods; constructors commonly use this form. section 3.2.3
  • Use &mut self when a method mutates the value; calling it requires a mutable reference. section 3.2.3

A stack implementation

For an RpnStack, RpnStack::new creates an empty stack, push(&mut self, value) adds a value, and pop(&mut self) returns a value or reports PopFromEmptyStack. An evaluator can create the stack with RpnStack::new(), then call stack.push(value) and stack.pop(). section 3.2.3

enum Error {
  InvalidNumber,
  PopFromEmptyStack,
}

impl RpnStack {  #1
  fn new() -> RpnStack {  #2
    RpnStack {
      stack: VecDeque::new(),
    }
  }

  fn push(&mut self, value: i32) {  #3
    self.stack.push_front(value);
  }

  fn pop(&mut self) -> Result<i32, Error> {
    match self.stack.pop_front() {
      Some(value) => Ok(value),
      None => Err(Error::PopFromEmptyStack),
    }
  }
}

Inspect the complete impl block showing a constructor, mutable methods, VecDeque storage, and an empty-stack error. section 3.2.3

How Refactoring to Rust covers it

How deep it goes
Explains definitions, self variants, mutability, and a working stack implementation, but does not develop advanced impl patterns.
Examples
Uses an RpnStack with new, push, pop, VecDeque storage, and evaluator calls.
What it assumes
Assumes basic Rust types and references while clarifying self parameters, mutability, and ownership control.
What you can do after
Build it from scratch by defining constructors and instance methods for a Rust type.
How it connects
Connects impl blocks with methods, associated functions, constructors, mutability, borrowing, ownership, and structs.

Also explained in

Compare how 3 books explain impl block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.