Unit-only enum to string slice in Rust 1.86
⚓ Rust 📅 2025-10-07 👤 surdeus 👁️ 4Goals
I have a unit-only enum, and I want a simple, lightweight way to convert each variant to a string slice which is known at compile time. When I say "lightweight," I'm thinking things like this:
- Easy for the compiler to inline.
- In terms of code size and execution speed, comparable to or better than the explicit lookup table implementation described below.
My particular setting has two extra features, which you can ignore if you want to give a more general answer:
- The string slice is used for string formatting, and perhaps will only be used for that.
- The variants' discriminants can serve as the indices of an array.
Existing suggestions
I've found a few suggestions for how to do this:
However, I can't tell how lightweight these implementations are (in the sense described above), and I'm curious about whether new Rust features might allow for nicer implementations.
Example implementations
These implementations all have the following code in common.
use SugarLevel::*;
enum SugarLevel {
NoSugar = 0,
HalfSugar = 1,
FullSugar = 2,
}
If you paste the common code followed by the example-specific code into the Rust Playground and hit Run, the program should print:
Buckwheat tea, no sugar
Tamarind tea, half sugar
Milk tea, full sugar
Matching method
This is based on the existing suggestions described above. I'm not sure how lightweight it is, but it's nice and simple from the programmer's perspective.
use std::fmt;
impl SugarLevel {
fn as_str(&self) -> &'static str {
match self {
NoSugar => "no sugar",
HalfSugar => "half sugar",
FullSugar => "full sugar",
}
}
}
impl fmt::Display for SugarLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
fn main() {
println!("Buckwheat tea, {NoSugar}");
println!("Tamarind tea, {HalfSugar}");
println!("Milk tea, {FullSugar}");
}
Explicit lookup table
This was suggested to me as something that might be especially lightweight, although it's less simple than I'd like from the programmer's perspective.
impl SugarLevel {
const STR: [&str; 3] = [
"no sugar",
"half sugar",
"full sugar",
];
}
fn main() {
println!("Buckwheat tea, {}", SugarLevel::STR[NoSugar as usize]);
println!("Tamarind tea, {}", SugarLevel::STR[HalfSugar as usize]);
println!("Milk tea, {}", SugarLevel::STR[FullSugar as usize]);
}
2 posts - 2 participants
🏷️ Rust_feed