The impl
keyword in Rust is used to implement some functionality on types. This functionality can include both functions and costs. There are two main kinds of implementations in Rust:
In this shot, we will focus on inherent implementations. You can learn more about trait implementations here.
Inherent implementations, as the name implies, are standalone. They are tied to a single concrete self
type that is specified after the impl
keyword. These implementations, unlike standard functions, are always in scope.
In the following program, we are adding methods to a Person
struct with the impl
keyword:
struct Person {name: String,age: u32}// Implementing functionality on the Person struct with the impl keywordimpl Person{// This method is used to introduce a personfn introduction(&self){println!("Hello! My name is {} and I am {} years old.", self.name, self.age);}// This method updates the age of the person on their birthdayfn birthday(&mut self){self.age = self.age + 1}}fn main() {// Instantiating a mutable Person objectlet mut person = Person{name: "Hania".to_string(), age: 23};// person introduces themself before their birthdayprintln!("Introduction before birthday:");person.introduction();// person ages one year on their birthdayperson.birthday();// person introduces themself after their birthdayprintln!("\nIntroduction after birthday:");person.introduction();}