In this blog post, we're going to see how to work with Enums in Rust
Enums
Enum is a type that can be any one of several variants. It is also called as Algebraic Data Types (ADT). Unlike other programming languages (ex: C), Enums in Rust can store data with it.
Enums helps to keep the code more concise. It eliminates the necessity to create multiple structs.
Declaring Enums
Enums can be declared using various ways.
Standard Enums
In this approach, declaring Enums just like any other programming language
enum Ack {
ExactlyOnce,
AtMostOnce,
AtLeastOnce
}
Complex Enums
If you would like to store data with Enum, you can use this approach. In this below example, we're creating an Enum which store variety of types with its variants
enum EnhancedAck {
ExactlyOnce,
AtMostOnce(String),
AtLeastOnce(i32, String)
}
Empty Enums
It is possible to create Empty Enums in Rust. This is also called as Zero-Sized Types. The main use case for an Empty Enum is type-level unreachability. For instance, suppose an API needs to return a Result in general, but a specific case actually is infallible.
enum Void {
}
Instantiating Standard Enums
Let us see how to instantiate Standard Enums. Instantiating Enum variants involves explicitly using the Enumβs name as its namespace, followed by one of its variants.
let a = Ack::ExactlyOnce;
println!("Received acknowledge {a:#?}");
Instantiating Complex Enums
When we've complex Enums like EnhancedAck Enum we've seen above, we need to specify the values as if we pass function arguments.
In case if you would like to access the data stored along with Enum variant, we can make use of if let
statement to retrieve the values as below
let b = EnhancedAck::ExactlyOnce;
println!("Received Acknowledge: {b:?}");
let c = EnhancedAck::AtMostOnce(String::from("Hello Rust"));
println!("Received Acknowledge: {c:?}");
if let EnhancedAck::AtMostOnce(c1) = c {
println!("Extracted data from Enum --> Message: {}", c1);
}
let d = EnhancedAck::AtLeastOnce(100, String::from("Hello Rust Again"));
println!("Received Acknowledge: {d:?}");
if let EnhancedAck::AtLeastOnce(d1, d2) = d {
println!("Extracted data from Enum --> Number: {}, Message: {}", d1, d2);
}
I hope this blog post gives you a brief overview about Enums.
All the code examples can be found in this link.
Please feel free to share your feedback.
Happy reading!!!
Top comments (0)