4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

目的

区分値をenumで扱いたい。区分値は例えば公開区分、公開(00101)、非公開(00102)、権限区分、一般(00201)、管理者(00202)のように最初の3桁が区分の種類を表し、残り2桁がその区分値の値を表します。

マクロ

よい感じのマクロがあります。string_enum
以下の機能を実装してくれます。

  • pub fn as_str(&self) -> &'static str
  • impl serde::Serilaize
  • impl serde::Deserilaize
  • impl FromStr
  • impl Debug
  • impl Display

足りないもの

Defaultが欲しいのでこれだけ自作します。

コード

Cargo.toml
[package]
name = "kbn"
version = "0.1.0"
edition = "2018"

[dependencies]
serde = "1.0.117"
serde_derive = "1.0.117"
serde_json = "1.0.59"
string_enum = "0.3.0"
main.rs
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate string_enum;

#[derive(StringEnum)]
pub enum PublishKbn {
    /// `00101`
    Public,
    /// `00102`
    NonPublic,
}

impl Default for PublishKbn {
    fn default() -> Self {
        PublishKbn::Public
    }
}

#[derive(StringEnum)]
pub enum AuthKbn {
    /// `00201`
    Normal,
    /// `00202`
    NonPublic,
}

impl Default for AuthKbn {
    fn default() -> Self {
        AuthKbn::Normal
    }
}

#[derive(Debug, Deserialize, Serialize, Default)]
pub struct MyStruct {
    publish_kbn: PublishKbn,
    auth_kbn: AuthKbn,
}

fn main() {
    let json = json!({
        "publish_kbn": "00101",
        "auth_kbn": "00202",
    });
    let res: MyStruct = serde_json::from_value(json).unwrap();
    println!("{:?}", res);
}


4
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?