9.6 Methods and Associated Functions
Methods are functions associated with a struct, allowing you to define behavior specific to your types and encapsulate functionality.
9.6.1 The impl
Block
Methods and associated functions are defined within an impl
(implementation) block for a struct.
impl StructName {
// Methods and associated functions go here
}
9.6.2 Associated Functions
Associated functions are functions that are tied to a struct but do not require an instance. These functions do not take self
as a parameter.
Example:
impl Person {
fn new(name: String, age: u8) -> Person {
Person { name, age }
}
}
- You call associated functions using the
StructName::function_name()
syntax.
fn main() {
let person = Person::new(String::from("Frank"), 40);
}
9.6.3 Methods
Methods are functions that operate on an instance of a struct. They take self
as the first parameter.
Defining Methods
impl StructName {
fn method_name(&self) {
// Method body
}
}
&self
is shorthand forself: &Self
, whereSelf
refers to the struct type.
Benefits of Methods
- Encapsulation: Methods encapsulate behavior related to a type.
- Namespace: Methods are namespaced by the struct, preventing name collisions.
- Method Syntax: Using methods enables a more object-oriented style of programming.
Example:
struct Person { name: String, age: u8, } impl Person { fn new(name: String, age: u8) -> Person { Person { name, age } } fn greet(&self) { println!("Hello, my name is {}.", self.name); } } fn main() { let person = Person::new(String::from("Grace"), 35); person.greet(); }
- In this example,
greet
is a method that operates on aPerson
instance.
Mutable Methods
If a method needs to modify the instance, it must take &mut self
.
fn update_age(&mut self, new_age: u8) {
self.age = new_age;
}
Consuming Methods
Methods can take ownership of the instance by using self
without a reference.
fn into_name(self) -> String {
self.name
}
Calling Methods
Methods are called using dot notation.
fn main() {
let mut person = Person::new(String::from("Grace"), 35);
person.update_age(36);
println!("{} is now {} years old.", person.name, person.age);
}