Skip to content

Commit

Permalink
feature: introduce strum
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Apr 7, 2024
1 parent 8d0ccf7 commit 80384ff
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ chrono = "0.4.37"
opentelemetry = "0.22.0"
opentelemetry-otlp = { version = "0.15.0", features = ["tonic"] }
opentelemetry_sdk = { version = "0.22.1", features = ["rt-tokio"] }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
thiserror = "1.0.58"
tracing = "0.1.40"
tracing-appender = "0.2.3"
Expand All @@ -23,4 +25,5 @@ derive_builder = "0.20.0"
derive_more = "0.99.17"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26.2", features = ["derive"] }
tokio = { version = "1.37.0", features = ["rt", "rt-multi-thread", "macros"] }
60 changes: 60 additions & 0 deletions examples/enum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use anyhow::Result;
use serde::Serialize;
use strum::{
Display, EnumCount, EnumDiscriminants, EnumIs, EnumIter, EnumString, IntoEnumIterator,
IntoStaticStr, VariantNames,
};

#[allow(unused)]
#[derive(Display, Debug, Serialize)]
enum Color {
#[strum(serialize = "redred", to_string = "red")]
Red,
Green {
range: usize,
},
Blue(usize),
Yellow,
#[strum(to_string = "purple with {sat} saturation")]
Purple {
sat: usize,
},
}

#[derive(
Debug, EnumString, EnumCount, EnumDiscriminants, EnumIter, EnumIs, IntoStaticStr, VariantNames,
)]
#[allow(unused)]
enum MyEnum {
A,
B(String),
C,
D,
}

fn main() -> Result<()> {
println!("{:?}", MyEnum::VARIANTS);
MyEnum::iter().for_each(|v| println!("{:?}", v));
println!("total: {:?}", MyEnum::COUNT);

let my_enum = MyEnum::B("hello".to_string());
println!("{:?}", my_enum.is_b());
let s: &'static str = my_enum.into();
println!("{}", s);

let red = Color::Red;
let green = Color::Green { range: 10 };
let blue = Color::Blue(20);
let yellow = Color::Yellow;
let purple = Color::Purple { sat: 30 };

println!(
"red: {}, green: {}, blue: {}, yellow: {}, purple: {}",
red, green, blue, yellow, purple
);

let red_str = serde_json::to_string(&red)?;
println!("{}", red_str);

Ok(())
}

0 comments on commit 80384ff

Please sign in to comment.