Converting an Enum to a String in Rust

The easiest way to convert an enum to a String in Rust is to implement the std::fmt::Display trait.

#[derive(Debug, Clone, Copy)]
enum Platform {

impl fmt::Display for Platform {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Platform::Linux => write!(f, "Linux"),
            Platform::Macos => write!(f, "macOS"),
            Platform::Windows => write!(f, "Windows"),
            Platform::Unknown => write!(f, "unknown"),

Then you can call the to_string() method.

fn main() {
    let platform: String = Platform::Unknown.to_string();

    println!("{}", platform);
$ cargo run
1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: programming, rust, tutorial

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!