5个稳定版本

使用旧的Rust 2015

1.0.5 2018年7月30日

#488调试

Download history 9/week @ 2023-11-27 1/week @ 2023-12-04 9/week @ 2023-12-11 6/week @ 2023-12-18 9/week @ 2024-01-08 5/week @ 2024-01-15 3/week @ 2024-01-22 20/week @ 2024-01-29 42/week @ 2024-02-05 52/week @ 2024-02-12 72/week @ 2024-02-19 33/week @ 2024-02-26 78/week @ 2024-03-04 71/week @ 2024-03-11

每月263次下载

MIT 许可证

16KB
335 代码行

serdebug

Travis CI GitHub license Crates.io docs.rs

这是一个#[derive(Debug)]的替换方案,它使用serde::Serialize来提供对输出序列化的高级控制。

用法

默认情况下,生成的代码将产生与#[derive(Debug)]完全相同的输出,以实现兼容性。

然而,这可能并不很有趣,所以让我们添加一些serde属性来看看我们如何控制调试表示

extern crate serde;

#[macro_use]
extern crate serde_derive;

#[macro_use]
extern crate serdebug;

pub struct CustomType(u32);

#[derive(Serialize, SerDebug)]
pub enum MyEnum {
    // renaming items works as expected
    #[serde(rename = "AAAAAAA!!!")]
    A,

    B(u32),

    C { flag: bool },
}

#[derive(Serialize, SerDebug)]
// so does bulk rename on containers
#[serde(rename_all = "PascalCase")]
pub struct MyStruct {
    number: u32,

    my_enum: Vec<MyEnum>,

    // we might want to hide some items from the output
    #[serde(skip_serializing)]
    hidden: bool,

    // or override serialisation for otherwise verbose wrappers or
    // third-party types that don't implement `Debug` and/or `Serialize`
    #[serde(serialize_with = "custom_serialize")]
    custom_type: CustomType,
}

fn custom_serialize<S: serde::Serializer>(value: &CustomType, ser: S) -> Result<S::Ok, S::Error> {
    use serde::Serialize;

    value.0.serialize(ser)
}

fn main() {
    let s = MyStruct {
        number: 42,
        my_enum: vec![MyEnum::A, MyEnum::B(10), MyEnum::C { flag: true }],
        hidden: true,
        custom_type: CustomType(20),
    };

    assert_eq!(format!("{:#?}", s), "
MyStruct {
    Number: 42,
    MyEnum: [
        AAAAAAA!!!,
        B(
            10
        ),
        C {
            flag: true
        }
    ],
    CustomType: 20
}
".trim());
}

依赖项

~2MB
~51K SLoC