Rust Lang

Rust Enum to String Conversion

In the Rust programming language, an enum refers to a data type that represents a variant of multiple possible types. Each variant is a unique value constructor for a particular set of possible values. It is defined by enumerating its possible variants where each variant is associated with a value of a specified type or no value.

Enums are extremely useful when you must represent a set of related values with different types or meanings.

For example, we can use enums to describe the various states of a user session such as “logged in”, “logged out”, or “banned.” Each state has its meaning and may require different data to represent it.

In this tutorial, we will learn how to convert an enum value into a string type. Unfortunately, unlike native data types, there are no methods of directly casting an enum to a string.

Convert an Enum to String in Rust

Let us start by defining a simple enum type in Rust. The code snippet is shown in the following:

enum UserSession {
    LoggedIn,
    LoggedOut,
    Banned,
}

 
LoggedIn, LoggedOut, and Banned are the three possible variants in this enum. A user can be in one of these states at any given time.

Method 1:

In Rust, we can implement the ToString trait on the enum to convert an enum to a string. This trait provides us with the to_string method which allows us to return a string representation of the value.

The following code snippet shows how to implement this trait on the target enum:

enum UserSession {
    LoggedIn,
    LoggedOut,
    Banned,
}

impl ToString for UserSession {
    fn to_string(&self) -> String {
        match self {
            UserSession::LoggedIn => String::from("User is logged in."),
            UserSession::LoggedOut => String::from("User is logged out."),
            UserSession::Banned => String::from("User is banned"),
        }
    }
}

 
In this example, we implement the ToString trait for the UserSession enum. In addition, we define the to_string method that returns a string representation of the enum value.

We also use a match statement to match the enum variant and return the corresponding string.

Now, we can convert a UserSession enum value to a string using the to_string method.

Example:

fn main() {
    let session = UserSession::LoggedIn;
    let session_str = session.to_string();
    println!("{}", session_str);
}

 
This should print the following string:

User is logged in.

 

Method 2:

Another method that we can use is using the built-in format! macro to convert the enum value to a string.

An example is as follows:

fn main() {
    let logged_out = UserSession::LoggedOut;
    let logged_out_str = format!("{}", logged_out);
    println!("{}", logged_out_str);
}

 
This also allows us to convert the enum value to a string.

NOTE: The format! macro simply calls the to_string method under the hood. Therefore, it is also necessary that the enum implements the display trait before calling the format method.

The implementation is as follows:

use std::fmt;

impl fmt::Display for UserSession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UserSession::LoggedIn => write!(f, "Logged In!"),
            UserSession::LoggedOut => write!(f, "Logged Out!"),
            UserSession::Banned => write!(f, "Banned!"),
        }
    }
}

 
You can then call the format! macro to convert the enum to a string.

Conclusion

You learned the basics of using enums to represent the data with related but different variants. You also discovered how to use various implementations to convert an enum value to a string.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list