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 {
Linux,
MacOS,
Windows,
Unknown,
}
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
unknown