Methods are similar to functions: they’re declared with the `fn` keyword and their name, they can have parameters and a return value, and they contain some code that is run when they’re called from somewhere else. However, methods are different from functions in that they’re defined within the context of a struct (or an enum or a trait object), and their first parameter is always `self`, which represents the instance of the struct the method is being called on.
```
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 { //method defined in the context of a struct
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle{width: 30, height: 50};
println!("The area of the rectangle is {} square pixels.", area(&rect1));
}
```
`impl` (implementation) block now contains the area `fn`. The first parameter is changed to `self` and used further. Methods can take ownership of `self`, borrow `self` immutably, or borrow `self` mutably. `&self` was used because we didn't want to take ownership as only reading the struct data was needed. If instance change was required the `&mut self` would have been used instead.
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("CAn rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
```
######Associated functions
`impl` block allows to define functions within it that don't take `self` as a parameter. These are called the associated functions because they're associated with the struct. They're not methods because they don't hava an instance of the struct to work with. They are often used as constructors that will return a new instance of the struct.
```
impl Rectangle {
fn square(size: u32) -> Rectangle { //associated function
Rectangle { width: size, height: size }
}
}
```
Each struct is allowed to have multiple `impl` blocks.