带有可选布尔值的YAML未命名字符串列表

I want to define YAML that defines a list of strings by default. I don't want this list of strings to be a named attribute. I also want to have an optional boolean parameter. As in

package main

import (
    "fmt"
    "log"

    yaml "gopkg.in/yaml.v2"
)

type ThingAndGroups struct {
    Groups   []string
    boolval  boolean
}

var someStr = `
thing1:
  - g1
  - g2
  boolval:
    y

thing2:
  - g1
  - g2
`

func main() {
    t := make(map[string]ThingAndGroups)

    err := yaml.Unmarshal([]byte(someStr), &t)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- t:
%v

", t)
}

Would then return

map[thing1:{[g1, g2] true}, thing2:{[g1, g2] false}]

Is that possible?

I DO NOT want to define the YAML as

var someStr = `
thing1:
  groups:
    - g1
    - g2
  boolval:
    y`

And if the YAML didn't have boolval I could just do

 func main() {
    // NOTE THIS IS A MAP
    t := make(map[string][]string)

    err := yaml.Unmarshal([]byte(someStr), &t)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- t:
%v

", t)
}

Problem

  • Defining a YAML sequence without using a mapping key.

Solution

  • Change BEFORE into AFTER

BEFORE

  var someStr = `
  thing1:
    - g1
    - g2
    boolval:
      y

  thing2:
    - g1
    - g2
  `

AFTER

  var someStr = `
  thing1:
    - g1
    - g2
    - boolval: y

  thing2:
    - g1
    - g2
  `

Pitfalls

  • This approach is not desirable because it uses the YAML sequence to store two different kinds of data (the groups and the boolean value).
  • Another answer (that was later deleted) suggested using a groups key, and that was a good suggestion.