< 返回我的博客

子十 发表于 2021-07-30 14:09

Tags:enum,String,枚举,字符串

Strum

枚举转字符串库:Strum docs.rs/stum

使用示例:

[dependencies]
strum = { version = "0.21.0", features = ["derive"] }
#[macro_use]
extern crate strum;

use std::str::FromStr;

#[derive(EnumString, Display, Debug, PartialEq)]
pub enum Colors {
  Red,
  Green
}

fn main() {
  let color: String = Colors::Red.to_string();
  println!("{}", color); // Red

  let new_color = "Green";
  if Colors::Green == Colors::from_str(new_color).unwrap() {
    println!("New color is {}", new_color);   // New Color is Green
  }
}

评论区

写评论

还没有评论

1 共 0 条评论, 1 页