#primitive #enums #derive #conversion #tryfrom #try-from

derive-try-from-primitive

为原始类型到枚举的转换自定义 derive try_from 方法

2 个版本 (1 个稳定版)

1.0.0 2020年3月30日
0.1.0 2017年7月12日

进程宏 中排名第 365

Download history 15188/week @ 2024-03-14 16968/week @ 2024-03-21 13973/week @ 2024-03-28 15774/week @ 2024-04-04 15791/week @ 2024-04-11 14726/week @ 2024-04-18 16395/week @ 2024-04-25 16519/week @ 2024-05-02 16569/week @ 2024-05-09 16870/week @ 2024-05-16 16906/week @ 2024-05-23 15643/week @ 2024-05-30 14574/week @ 2024-06-06 16827/week @ 2024-06-13 14939/week @ 2024-06-20 10465/week @ 2024-06-27

每月下载量 59,798
12 Crates 中使用(8 直接使用)

MIT/Apache

10KB
191

示例

use core::convert::TryFrom;
use derive_try_from_primitive::TryFromPrimitive;


#[derive(TryFromPrimitive)]
#[repr(u16)]
enum Foo {
    Bar,
    Baz = 100,
    Quix = 200,
}

// Generated Code:
impl core::convert::TryFrom<u16> for Foo {
    type Error = u16;

    fn try_from(n: 16) -> Result<Self, Self::Error> {
        match n {
            0 => Ok(Foo::Bar),
            100 => Ok(Foo::Baz),
            200 => Ok(Foo::Quix),
            _ => Err(n),
        }
    }
}

fn main() {
    let bar = Foo::try_from(0);
    let baz = Foo::try_from(100);
    let quix = Foo::try_from(200);
    let bad = Foo::try_from(300);
    assert_eq!(bar.unwrap() as u16, 0);
    assert_eq!(baz.unwrap() as u16, 100);
    assert_eq!(quix.unwrap() as u16, 200);
    if let Err(value) = bad {
        assert_eq!(value, 300, "Input is returned for convenience");
    }
}

依赖项

~1.5MB
~35K SLoC