Rust枚举显示库enum-display的使用:为枚举类型自动生成友好的Display实现

Rust枚举显示库enum-display的使用:为枚举类型自动生成友好的Display实现

enum-display 是一个通过宏为枚举变体实现 std::fmt::Display 的库。

简单示例

use enum_display::EnumDisplay;

#[derive(EnumDisplay)]
enum Color {
  Red,
  Green,
  Blue,
}

assert_eq!(Color::Red.to_string(), "Red");
assert_eq!(Color::Green.to_string(), "Green");
assert_eq!(Color::Blue.to_string(), "Blue");

自定义大小写转换示例

支持来自 convert_case 的任何大小写转换格式。

use enum_display::EnumDisplay;

#[derive(EnumDisplay)]
#[enum_display(case = "Kebab")]
enum Message {
    HelloGreeting { name: String },
}

assert_eq!(Message::HelloGreeting { name: "Alice".to_string() }.to_string(), "hello-greeting");

完整示例代码

下面是一个更完整的示例,展示如何使用 enum-display 为枚举自动生成 Display 实现:

// 首先在Cargo.toml中添加依赖
// enum-display = "0.1.4"

use enum_display::EnumDisplay;

// 基本枚举示例
#[derive(EnumDisplay)]
enum HttpStatus {
    Ok,
    NotFound,
    InternalServerError,
}

// 带参数的枚举示例
#[derive(EnumDisplay)]
#[enum_display(case = "Snake")]
enum ApiError {
    InvalidRequest,
    Unauthorized,
    RateLimitExceeded { retry_after: u64 },
}

// 使用不同的命名转换风格
#[derive(EnumDisplay)]
#[enum_display(case = "Title")]
enum UserRole {
    Administrator,
    Moderator,
    RegularUser,
}

fn main() {
    // 基本枚举使用
    println!("HTTP状态: {}", HttpStatus::Ok); // 输出: HTTP状态: Ok
    
    // 带参数的枚举(注意参数不会显示)
    println!("API错误: {}", ApiError::RateLimitExceeded { retry_after: 60 }); // 输出: API错误: rate_limit_exceeded
    
    // 不同命名风格
    println!("用户角色: {}", UserRole::RegularUser); // 输出: 用户角色: Regular User
    
    // 转换为字符串
    let status_str = HttpStatus::NotFound.to_string();
    assert_eq!(status_str, "NotFound");
}

安装

在项目中运行以下Cargo命令:

cargo add enum-display

或者在Cargo.toml中添加:

enum-display = "0.1.4"

支持的命名转换格式

enum-display 支持以下命名转换格式(通过 convert_case 库):

  • "Upper" - 全部大写
  • "Lower" - 全部小写
  • "Title" - 标题格式
  • "Camel" - 驼峰式
  • "Snake" - 蛇形式
  • "Kebab" - 短横线式
  • "Pascal" - 帕斯卡式(与默认行为相同)
  • "ScreamingSnake" - 尖叫蛇形式

使用时只需在枚举上添加 #[enum_display(case = "格式")] 属性即可。


1 回复

Rust枚举显示库enum-display的使用指南

enum-display是一个Rust库,用于为枚举类型自动生成友好的Display trait实现,简化枚举值的显示输出。

安装

Cargo.toml中添加依赖:

[dependencies]
enum-display = "0.1"

基本用法

使用#[derive(Display)]宏来自动为枚举生成Display实现:

use enum_display::Display;

#[derive(Display)]
enum Status {
    Running,
    Stopped,
    Error(String),
}

示例

简单枚举

#[derive(Display)]
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    println!("Color: {}", Color::Red);  // 输出: Color: Red
}

带数据的枚举

#[derive(Display)]
enum HttpStatus {
    Ok,
    NotFound,
    ServerError(String),
}

fn main() {
    println!("Status: {}", HttpStatus::Ok);  // 输出: Status: Ok
    println!("Status: {}", HttpStatus::ServerError("Database connection failed".to_string()));
    // 输出: Status: ServerError(Database connection failed)
}

自定义显示格式

你可以使用#[display]属性来自定义显示格式:

#[derive(Display)]
enum LogLevel {
    #[display("DEBUG")]
    Debug,
    #[display("INFO")]
    Info,
    #[display("WARN")]
    Warning,
    #[display("ERROR")]
    Error,
}

fn main() {
    println!("Level: {}", LogLevel::Warning);  // 输出: Level: WARN
}

带参数的格式化

#[derive(Display)]
enum Shape {
    #[display("Circle with radius {0}")]
    Circle(f64),
    #[display("Rectangle {0}x{1}")]
    Rectangle(f64, f64),
}

fn main() {
    println!("{}", Shape::Circle(5.0));  // 输出: Circle with radius 5
    println!("{}", Shape::Rectangle(4.0, 3.0));  // 输出: Rectangle 4x3
}

高级用法

使用枚举的字段名

#[derive(Display)]
enum Person {
    #[display("{name} (age: {age})")]
    Adult { name: String, age: u8 },
    #[display("Child: {0}")]
    Child(String),
}

fn main() {
    let adult = Person::Adult {
        name: "Alice".to_string(),
        age: 30,
    };
    println!("{}", adult);  // 输出: Alice (age: 30)
}

忽略某些字段

#[derive(Display)]
enum Config {
    #[display("Database config: {host}:{port}")]
    Database {
        host: String,
        port: u16,
        username: String,
        #[display(ignore)]
        password: String,
    },
}

fn main() {
    let db_config = Config::Database {
        host: "localhost".to_string(),
        port: 5432,
        username: "admin".to_string(),
        password: "secret".to_string(),
    };
    println!("{}", db_config);  // 输出: Database config: localhost:5432
}

完整示例代码

下面是一个综合使用enum-display各种特性的完整示例:

use enum_display::Display;

// 简单枚举示例
#[derive(Display)]
enum Color {
    Red,
    Green,
    Blue,
}

// 带数据的枚举示例
#[derive(Display)]
enum HttpStatus {
    Ok,
    NotFound,
    ServerError(String),
}

// 自定义显示格式示例
#[derive(Display)]
enum LogLevel {
    #[display("DEBUG")]
    Debug,
    #[display("INFO")]
    Info,
    #[display("WARNING")]  // 自定义显示文本
    Warning,
    #[display("CRITICAL")]
    Error,
}

// 带参数的格式化示例
#[derive(Display)]
enum Shape {
    #[display("圆形(半径: {0})")]  // 使用中文格式
    Circle(f64),
    #[display("矩形: {0}x{1}")]
    Rectangle(f64, f64),
}

// 使用字段名的示例
#[derive(Display)]
enum Person {
    #[display("成年人: {name}, {age}岁")]
    Adult { name: String, age: u8 },
    #[display("儿童: {0}")]
    Child(String),
}

// 忽略字段的示例
#[derive(Display)]
enum Config {
    #[display("数据库配置 - 主机: {host}, 端口: {port}")]
    Database {
        host: String,
        port: u16,
        #[display(ignore)]
        username: String,
        #[display(ignore)]
        password: String,
    },
}

fn main() {
    // 简单枚举使用
    println!("颜色: {}", Color::Red);
    
    // 带数据的枚举使用
    println!("HTTP状态: {}", HttpStatus::Ok);
    println!("HTTP状态: {}", HttpStatus::ServerError("数据库连接失败".to_string()));
    
    // 自定义显示格式
    println!("日志级别: {}", LogLevel::Warning);
    
    // 带参数的格式化
    println!("形状: {}", Shape::Circle(5.0));
    println!("形状: {}", Shape::Rectangle(4.0, 3.0));
    
    // 使用字段名
    let adult = Person::Adult {
        name: "张三".to_string(),
        age: 35,
    };
    println!("人物: {}", adult);
    
    // 忽略字段
    let db_config = Config::Database {
        host: "127.0.0.1".to_string(),
        port: 3306,
        username: "root".to_string(),
        password: "123456".to_string(),
    };
    println!("配置: {}", db_config);
}

注意事项

  1. 默认情况下,枚举变体会显示其名称
  2. 可以为每个变体单独指定显示格式
  3. 可以使用字段名或位置索引来引用字段值
  4. 可以忽略不想显示的字段

enum-display库提供了一种简洁的方式来为枚举类型实现Display trait,避免了手动实现的样板代码,同时提供了足够的灵活性来自定义显示格式。

回到顶部