The Rust Programming Language — Pattern Matching — Methods
Rust provides us with a way we can define methods on the an enum namespace. It provides us with impl keyword. Methods allow you to call the lines of code in context of certain namespaces. We use methods when the function calls are associated to a particular type, for e.g. enums. Methods are associated functions called on a instance of particular type.
So we have an enum Color and we want to introduce a method to it. We’ll write 2 methods on the enum Color named rgb and new. So we’ll have 2 methods in the scope of Color.
Let’s take a look at below code snippet:
enum Color {
Red,
Yellow,
Green,
Custom { red: u8, green: u8, blue: u8 }
}
impl Color {
fn rgb(color: Color) -> (u8, u8, u8) {
match color {
Color::Red => (255, 0, 0),
Color::Yellow => (255, 255, 0),
Color::Green => (0, 255, 0),
Color::Custom { red, green, blue } => (red, green, blue)
}
}
fn new(r: u8, g: u8, b: u8) -> Color {
Color::Custom { red: r, green: g, blue: b }
}
}
fn main() {
let current_color: Color = Color::Green;
let color_description = match current_color {
Color::Red => {
"The color is Red!"
}
Color::Yellow => {
"The color is Yellow!"
}
_ => {
"The color is a different color!"
}
};
let color = Color::new(255, 0, 0);
let rgb = Color::rgb(color);
println!("{} {} {}", rgb.0, rgb.1, rgb.2);
}Observations:
- We have a separate declaration section of methods on
Colorusingimplkeyword.implstands for Implementation. - We define methods inside Color using
fnkeyword. Just asenumwe don’t have comma separation for multiplemethods. - These methods can accept any type of input or can return any type of output including the type they are associated with, i.e.
Color. - We can call these methods using namespace of they type on which they have been defined, i.e. using
::.Color::new(255, 0, 0)is an example of how we can call a method.
So we saw above that we can call the methods using namespace i.e. ::. But we can also use chaining mechanism to rather call a method just like we call a method on an object in other languages, using dot .. For e.g. color.new(10, 20, 30). Rust provides us two more keywords self and Self which allows us to use dot . for making function calls. self and Self are only used inside impl. self means give me one of the types of variants impl is on, in our case, variants of Color. Self with ‘S’ refers to Color itself.
self:
- The lowercase
selfis a keyword in Rust used within methods to refer to the current instance of the type. - It is typically used in method definitions and method calls to operate on the instance itself.
- It is a reference to the instance and is used as a parameter for instance methods.
Self:
Selfis a special keyword used to refer to the current type or the type in which it is used.- Self is typically used as a return type of methods
- The return type refers to the
enumitself.
Take a look at below code snippet for an example of self and Self:
enum Color {
Red,
Yellow,
Green,
Custom { red: u8, green: u8, blue: u8 }
}
impl Color {
// Associated function that creates a custom Color
fn custom_color(r: u8, g: u8, b: u8) -> Self {
Color::Custom { red: r, green: g, blue: b }
}
// Method that prints information about the Color
fn describe(&self) {
match self {
Self::Red => {
println!("The color is Red!");
}
Self::Yellow => {
println!("The color is Yellow!");
}
Self::Green => {
println!("The color is Green!");
}
Self::Custom { red, green, blue } => {
println!("Custom color: R={}, G={}, B={}", red, green, blue);
}
}
}
}
fn main() {
let red_color = Color::Red;
let custom_color = Color::custom_color(255, 0, 0);
red_color.describe();
custom_color.describe();
}Observations:
- We used
selfkeyword as a parameter ofdescribemethod. - This
selfkeyword basically represents all the variants ofColorenum. Selfbasically referes toColorinside which the methods are declared.
I hope you enjoyed this article on how to write methods in Rust. Please share your feedback in the comments section.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.






