如何解析包含简单列表和键值列表(关联数组)的 YAML

how to parse a YAML containing a simple list together with a key-value list (associative array)

我有以下 YAML:

build:
  - step 1
  - step 2

  - name: step 3
    do: something

  - name: step 4
    get: fetch ...

  - name: step 5
    put: upload something

为了解析它,我正在尝试使用这个

#[derive(Debug, Deserialize, PartialEq)] 
struct Config {
  build: Option<Vec<Steps>>
}

#[derive(Debug, Deserialize, PartialEq)]
struct Build {
    #[serde(flatten)]
    item: String,
    steps: Steps,
}

#[derive(Debug, Deserialize, PartialEq)]
struct Steps {
    name: String,
    r#do: Option<String>,
    put: Option<String>,
    get: Option<String>,
}

但是我得到这个错误:

Error parsing configuration file: build[0]: invalid type: string "step 1", expected struct Build

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0ddb0eb8be0888e74b089eb0ebc5daee

我只能解析:

build:
 - step 1
 - step 2

使用这个:

#[derive(Debug, Deserialize, PartialEq)]
struct Config {
   build: Option<Vec<String>>
}

或者:

 build:
 - name: step 1
   do: foo
 - name: step 2
   do: bar

使用:

#[derive(Debug, Deserialize, PartialEq)]
struct Config {
   build: Option<Vec<Steps>>
} 

但是找不到同时拥有这两个选项的方法,知道如何解析吗?

使用枚举:

#[derive(Debug, serde::Deserialize, PartialEq)]
struct Build {
    build: Vec<Foo>,
}

#[derive(Debug, serde::Deserialize, PartialEq)]
#[serde(untagged)]
enum Foo {
    Step(Step),
    Bar(String),
}

#[derive(Debug, serde::Deserialize, PartialEq)]
struct Step {
    name: String,
    #[serde(rename = "do")]
    make: Option<String>,
    put: Option<String>,
    get: Option<String>,
}

fn main() -> Result<(), serde_yaml::Error> {
    let input = r#"build:
  - step 1
  - step 2

  - name: step 3
    do: something

  - name: step 4
    get: fetch ...

  - name: step 5
    put: upload something"#;

    let build: Build = serde_yaml::from_str(input)?;

    println!("{:#?}", build);

    Ok(())
}