impl Block (Rust)
An impl block attaches methods and associated functions to a struct, enum, or trait. It is where the behavior of a type lives, separate from the data definition.
Rust
Rust separates data (struct/enum) from behavior (impl). Inside impl Type { ... } you define methods whose first parameter is self, &self, or &mut self (called with dot syntax) and associated functions with no self (called with Type::name, like the conventional new constructor).
impl Trait for Type is a special form that implements a trait's methods for your type, plugging it into Rust's polymorphism system. You can have many impl blocks for one type — for example, organizing methods or adding behavior conditionally with generic bounds.
The keyword impl also appears in signatures as impl Trait, meaning 'some concrete type that implements this trait' — useful for returning closures or iterators without naming their unspeakable types.
Syntax
impl Counter {
fn new() -> Self { Counter { n: 0 } }
fn bump(&mut self) { self.n += 1; }
}Examples
Rust
struct Counter { n: i32 }
impl Counter {
fn new() -> Self { Counter { n: 0 } }
fn bump(&mut self) { self.n += 1; }
}
fn main() {
let mut c = Counter::new();
c.bump();
c.bump();
println!("{}", c.n);
}Output:
2