An `impl` block gives a struct or enum functions related to it. Write `impl` followed by the type name, then put the functions inside `{}`. It is a common next step after defining your own type. section 4.1.5 section 4.4
The functions inside can work in two ways:
- A method takes `self` in some form. Use `&self` to work with a reference, or `&mut self` when the method needs to change the value. Call it with a dot, as in `my_mood.check()`. section 4.1.5 section 4.4
- An associated function does not take `self`. Call it through the type with `::`, as in `Animal::new_cat()`. Such functions often create a new value. section 4.1.5
enum Mood {
Good,
Bad,
Sleepy,
}
impl Mood {
fn check(&self) {
match self {
Mood::Good => println!("Feeling good!"),
Mood::Bad => println!("Eh, not feeling so good"),
Mood::Sleepy => println!("Need sleep NOW"),
}
}
}
fn main() {
let my_mood = Mood::Sleepy;
my_mood.check();
}
Here, `impl Mood` adds `check` to an enum. The method looks at the value through `&self`, matches its variant, and prints a message. `my_mood.check()` calls it. section 4.1.5
`Self` with a capital S means the type being implemented; lowercase `self` means the particular value a method is called on. The dot operator also handles dereferencing references when calling methods, so you usually do not need to write extra `*` and `&` just to make a call. section 4.1.5 section 4.3
An `impl` block can also give a type a trait’s behavior. The form `impl Trait for Type` can use a trait’s provided methods or supply its own implementation. Some traits, such as `Debug`, can instead be added with `#[derive(Debug)]`; behavior Rust cannot guess must be implemented manually. section 7.1
impl<T: Copy> Cell<T> {
pub fn get(&self) -> T {
// Function details...
}
pub fn update<F>(&self, f: F) -> T
where
F: FnOnce(T) -> T,
{
// Function details...
}
}
A later pattern places methods in a separate `impl<T: Copy> Cell<T>` block. The `Copy` requirement means those methods are available only when the inner type implements `Copy`. section 13.1.3


