首页 > 解决方案 > YAML 枚举对象表示

问题描述

我有这个用例,我将在 Rust 中解释。我如何在 YAML 中表示等价物

enum MainEnum {
    Opt1(T1),
    Opt2(T2)
}

struct T1 {
   x: u32,
}

struct T2 {
   y: bool
}

我如何在 YAML 中表示这个?我希望 YaML 具有 x 字段或 y 字段,具体取决于在 YAML 中选择的 Enum 值。

该程序不运行。有任何想法吗?

use serde_yaml;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct T1 {
    x: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct T2 {
    y: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum MainEnum {
    Opt1(T1),
    Opt2(T2),
}

fn main() {
     let config = r#"
---
- Opt1
    x: "true"
"#;

     let me: MainEnum = serde_yaml::from_str(&config).unwrap();
     println!("{:?}", me);
}

运行时错误:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Scan(ScanError { mark: Marker { index: 17, line: 4, col: 5 }, info: "mapping values are not allowed in this context" })', src/main.rs:27:25

标签: rustyaml

解决方案


第一个问题似乎是您使用的 YAML 语法。对于 YAML 中的地图,您需要使用:so终止父级

     let config = r#"
---
- Opt1:
  x: true
"#;

实际上是正确的 YAML。但是,由于您向 serde_yaml 询问 MainEnum 的一个实例,而不是 MainEnum 的列表(例如 vec),因此它不需要 YAML 序列而是单个条目:

fn main() {
     let config = r#"
---
Opt1:
  x: true
"#;

     let me: MainEnum = serde_yaml::from_str(&config).unwrap();
     println!("{:?}", me);
}

这个解析:https ://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=029279e1e6baa77611c2a36e7d5bc3a4


推荐阅读