Logo

dev-resources.site

for different kinds of informations.

Working with Enums in Rust

Published at
1/24/2023
Categories
rust
enum
Author
ssivakumar
Categories
2 categories in total
rust
open
enum
open
Author
10 person written this
ssivakumar
open
Working with Enums in Rust

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
}
Enter fullscreen mode Exit fullscreen mode
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)
}
Enter fullscreen mode Exit fullscreen mode
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 {
}
Enter fullscreen mode Exit fullscreen mode
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:#?}");
Enter fullscreen mode Exit fullscreen mode
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);
    }
Enter fullscreen mode Exit fullscreen mode

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!!!

enum Article's
30 articles in total
Favicon
Mastering ENUMs in Go
Favicon
The 3 kinds of Enum in Rails
Favicon
Enhancing Enum Constants in Laravel with Description and Label Attributes
Favicon
Should I stay or should I go? Enums in TypeScript - error case study
Favicon
Effective Enum
Favicon
Result in Rust: another way of error handling
Favicon
How to convert a TypeScript built-in enum to a GraphQL enum
Favicon
Leveraging Enums in Angular: Enhancing Code Clarity and Reliability
Favicon
Typescript enum vs. "as const"
Favicon
Enum Fábrica Solitão em Java
Favicon
Implementing Enums in Golang
Favicon
Elixirでリストの最初の要素を取得
Favicon
[JS TS] How to create an object with keys based on enum
Favicon
Enum ou Enumerations no PHP
Favicon
Replacing If-Else Statements with Enums in Java
Favicon
Dart enhanced enum with custom values
Favicon
Working with Enums in Rust
Favicon
Modelando algoritmos complexos com enum
Favicon
Managing Task Status Transitions in TypeScript with Enums and Object Mapping
Favicon
TypeScript Enum's vs Discriminated Unions
Favicon
Strategy Pattern no Spring Boot Usando Enum
Favicon
Problem in C Pointer
Favicon
Merge TypeScript Enums
Favicon
Agora sim, o grande ganho do enum no Dart 2.17
Favicon
How to proper use ambient enum from Definition file
Favicon
O Poder da Classe Enum com métodos abstratos
Favicon
Refactoring code with the Strate Pattern
Favicon
🔥Input Enums for a better Development Experience 🔥 😋✂️
Favicon
O pequeno grande ganho do enum no Dart 2.15
Favicon
Typescript enums drawbacks and solutions

Featured ones: