In Rust, an enum is a data structure that declares its different subtypes. An enum enables the same functionality as a struct, but it does so with less code. For example, implementing different types of Machine
, where each machine has a different set of attributes, requires a different struct for each machine. On the other hand, we can incorporate all of these different types of machines into a single enum:
struct Phone {}struct Adder {x: i,y: i,}struct Computer {name: String,}
Additionally, creating a function that can take any type of Machine
as its parameter is not possible using structs; in such a case, enums must be used. With an enum, the type of machine can be identified inside the function by using pattern matching with the match keyword.
#![allow(unused_variables)]fn main() {#[allow(dead_code)]enum Machine {Phone,Adder(i8, i8),Computer(String),}// A function taking any Machine as parameter:fn foo(m: Machine) {match m {Machine::Phone => println!("This is a phone"),Machine::Adder(a, b) => println!("Sum: {}", a + b),Machine::Computer(name) => println!("Name: {}", name),}}let machine_1 = Machine::Phone;let machine_2 = Machine::Adder(3, 4);let machine_3 = Machine::Computer("Mainframe".to_string());foo(machine_1);foo(machine_2);foo(machine_3);}
A function can also be declared for an enum using the impl
keyword, which is similar to a struct:
#![allow(unused_variables)]fn main() {#[allow(dead_code)]enum Machine {Phone,Adder(i8, i8),Computer(String),}impl Machine{fn foo(&self) {match self {Machine::Phone => println!("This is a phone"),Machine::Adder(a, b) => println!("Sum: {}", a + b),Machine::Computer(name) => println!("Name: {}", name),}}}let machine_1 = Machine::Phone;let machine_2 = Machine::Adder(3, 4);let machine_3 = Machine::Computer("Mainframe".to_string());machine_1.foo();machine_2.foo();machine_3.foo();}
Free Resources