Enum is a symbolic name for a set of values. Enums are treated as data types, and you can use them to create sets of constants for use with variables and properties. It offers an easier way to work with sets of related constants.
we use the Keyword enum
to define an enum.
RUST ENUM Example
enum cloudController {
S3,
SFTP
}
fn main() {
let choose_cloud = cloudController::SFTP;
match choose_cloud {
cloudController::S3 => println!(" We choose to use s3 cloud "),
cloudController::SFTP=> println!(" WE choose to use SFTP protocol")
}
}
Adding Functionality to ENUMS using Implementation
Like Structs, we can add functionalities for enums using the implementation block
Here is an example, where we extend the functionality to get the fare of the mode of transportation we choose from the enum
.
// ENUM type declaration
enum VechicleType {
Car,
Train,
Aeroplane,
}
impl VechicleType {
fn cost_to_drive(self) -> u32 {
let cost: u32 = match self {
VechicleType::Car => 100,
VechicleType::Train => 500,
VechicleType::Aeroplane => 200,
};
cost
}
}
fn main () {
let my_vechicle: VechicleType = VechicleType::Car;
println!("cost to drive is {:?}", my_vechicle.cost_to_drive())
}
Passing Values inside ENUMS
We can also pass values to the variants inside the enum. Checkout the given below example.Where we are adding kilometers to the cost_to_drive method.
// ENUM type declaration
enum VechicleType {
Car(u32),
Train(u32),
Aeroplane(u32),
}
impl VechicleType {
fn cost_to_drive(&self) -> u32 {
let cost: u32 = match self {
VechicleType::Car(km) => km * 100,
VechicleType::Train(km) => km * 500,
VechicleType::Aeroplane(km) => km * 200,
};
cost
}
}
fn main () {
let distance: u32 = 45;
let my_vechicle: VechicleType = VechicleType::Car(distance);
println!("cost to drive is {:?}", my_vechicle.cost_to_drive())
}
How RUST ENUMS are different from Classes from other programming languages
- Enums and classes are both used to define custom types, but they have different purposes.
- Classes are used to define objects, which are instances of the class. Enums, on the other hand, are used to define a set of named values.
- Classes can have methods and properties, and can be used to define complex behaviors. Enums, on the other hand, are used to define a set of related values that can be used in a more limited way. They are often used to define constants or options.
In summary, classes are used to define objects with complex behaviors, while enums are used to define a set of related values that can be used in a more limited way.