`impl`
An impl block attaches functions to a type. impl Session holds inherent methods. impl Trait for Session is the type's implementation of a trait.
Detailed Explanation
A type declaration does not contain methods. After struct Session { ... } you write impl Session { fn new(...) -> Self { ... } }. Those functions are inherent: they belong to Session itself, not to a trait. You call them as session.expire() or Session::new(...). Several impl Session blocks are allowed, so you can group constructors in one and mutators in another, even across files in the same module.
impl Display for Session is different. That block says Session implements the Display trait, and it must provide every required method. You can only write this impl if you own the trait or you own the type (the orphan rule). Inherent impls have a similar restriction: you cannot write impl Vec<u8> in your crate because you do not own Vec.
impl blocks may be generic: impl<T> Stack<T> { ... } and impl<T: Display> Stack<T> { ... }. The second block exists only when T implements Display, so you can offer fn print(&self) without requiring Display on every Stack. Trait impls can be generic the same way: impl<T: Display> Display for Stack<T>.
Inside the block, Self means the type being implemented. Self in impl Session is Session. Self in impl<T> Stack<T> is Stack<T>. Associated functions use it as the return type of constructors: fn new() -> Self. Associated types appear in trait impls: type Err = io::Error.
There is no inheritance of impl blocks. A wrapper struct does not receive the inner type's inherent methods. You write forwarding methods, or you implement a shared trait on both types, or — rarely — you implement Deref so method lookup walks through.
What it costs: inherent methods are ordinary static calls. Trait methods are static calls too when the compiler knows the concrete type, and virtual calls only through dyn Trait. The compile-time cost is the number of monomorphised copies of a generic impl.
When you write impl Type: constructors and behaviour that is true of the type in every context. When you write impl Trait for Type: the type is answering a shared contract. Keep both next to the type definition unless the impl is huge.
Code Examples
struct Counter {
n: u32,
}
impl Counter {
fn new() -> Self {
Self { n: 0 }
}
fn bump(&mut self) {
self.n += 1;
}
}
fn main() {
let mut c = Counter::new();
c.bump();
println!("{}", c.n); // prints: 1
}Common Gotchas
You cannot `impl` a foreign type inherently
`impl Vec<String> { ... }` in your crate is rejected. Write an extension trait and `impl` that trait for `Vec<String>`.
Orphan rule for trait impls
`impl ForeignTrait for ForeignType` is illegal. Wrap the type in a newtype you own.
Multiple `impl Type` blocks are fine
Split them for readability. They must still live in the crate that owns the type.
`Self` is the implemented type
In `impl<T> Wrap<T>`, `Self` is `Wrap<T>`, not `T`. Return `Self` from constructors.