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!"
}
_ => {…