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


