A method is a function attached to a type. To give a struct or enum methods, write an `impl` block. A regular method takes `self` in some form and is usually called with a dot, as in `value.method()`. section 4.1.5
The form of `self` tells you how the method uses the value:
- `&self` lets the method use the value through a reference. section 4.1.5
- `&mut self` lets the method change the value. section 4.1.5
- `self` takes the value itself. section 4.1.5
A function in an `impl` block that does not take `self` is an associated function. Call it through the type with `::`, as in `String::from()` or `Vec::new()`. Associated functions often create new values. `Self` with a capital S means the type; lowercase `self` means the particular value. section 4.1.5
#[derive(Debug)]
enum AnimalType {
Cat,
Dog,
}
#[derive(Debug)]
struct Animal {
age: u8,
animal_type: AnimalType,
}
impl Animal {
fn new_cat() -> Self { #1
Self { #2
age: 10,
animal_type: AnimalType::Cat,
}
}
fn check_type(&self) {
match self.animal_type {
AnimalType::Dog => println!("The animal is a dog"),
AnimalType::Cat => println!("The animal is a cat"),
}
}
fn change_to_dog(&mut self) { #3
self.animal_type = AnimalType::Dog;
println!("Changed animal to dog! Now it's {self:?}");
}
fn change_to_cat(&mut self) {
self.animal_type = AnimalType::Cat;
println!("Changed animal to cat! Now it's {self:?}");
}
}
fn main() {
let mut new_animal = Animal::new_cat(); #4
new_animal.check_type();
new_animal.change_to_dog();
new_animal.check_type();
new_animal.change_to_cat();
new_animal.check_type();
}
This `impl Animal` block puts a constructor and two kinds of regular method together: `new_cat()` returns a new `Self`, `check_type(&self)` checks a value, and `change_to_dog(&mut self)` changes one. section 4.1.5
The dot is helpful when you have a reference. A `String` method such as `.is_empty()` can be called even on a `&&String`: Rust dereferences as needed to reach the type and supplies the reference the method needs. You usually do not have to write the `*` operators yourself for a method call. section 4.3
Methods can also come from traits. Implementing a trait for a type gives it the trait’s methods; the type can still have its own separate methods. section 7.1



















