File: enum_external.rs

package info (click to toggle)
rustc 1.86.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid
  • size: 913,560 kB
  • sloc: xml: 158,127; python: 35,921; javascript: 19,689; sh: 19,600; cpp: 18,906; ansic: 13,124; asm: 4,376; makefile: 708; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (45 lines) | stat: -rw-r--r-- 1,041 bytes parent folder | download | duplicates (23)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! An example showing off the usage of `Deserialize` to automatically decode
//! TOML into a Rust `struct`, with enums.

#![deny(warnings)]
#![allow(dead_code)]

use serde::Deserialize;

/// This is what we're going to decode into.
#[derive(Debug, Deserialize)]
struct Config {
    plain: MyEnum,
    plain_table: MyEnum,
    tuple: MyEnum,
    #[serde(rename = "struct")]
    structv: MyEnum,
    newtype: MyEnum,
    my_enum: Vec<MyEnum>,
}

#[derive(Debug, Deserialize)]
enum MyEnum {
    Plain,
    Tuple(i64, bool),
    NewType(String),
    Struct { value: i64 },
}

fn main() {
    let toml_str = r#"
    plain = "Plain"
    plain_table = { Plain = {} }
    tuple = { Tuple = { 0 = 123, 1 = true } }
    struct = { Struct = { value = 123 } }
    newtype = { NewType = "value" }
    my_enum = [
        { Plain = {} },
        { Tuple = { 0 = 123, 1 = true } },
        { NewType = "value" },
        { Struct = { value = 123 } }
    ]"#;

    let decoded: Config = toml::from_str(toml_str).unwrap();
    println!("{:#?}", decoded);
}