1 回答

TA贡献1829条经验 获得超13个赞
您发布的代码包含多个错误,包括 struct field Type
。您的代码中提供的 yaml 无效。这将导致在将 yaml 解组为结构时出错。
在 go 中解组 yaml 时,要求:
解码值的类型应与输出中的相应值兼容。如果一个或多个值由于类型不匹配而无法解码,解码将继续部分进行,直到 YAML 内容结束,并返回一个 *yaml.TypeError,其中包含所有缺失值的详细信息。
与此同时:
结构字段只有在导出时才会被解组(首字母大写),并且使用小写的字段名称作为默认键进行解组。
定义标签时也有错误yaml
,其中包含空格。自定义键可以通过字段标签中的“yaml”名称来定义:第一个逗号之前的内容用作键。
type Runners struct {
runners string `yaml:"runners"` // fields should be exportable
name string `yaml:”name”`
Type: string `yaml: ”type”` // tags name should not have space in them.
command [] Command
}
要使结构可导出,请将结构和字段转换为大写首字母并删除 yaml 标签名称中的空格:
type Runners struct {
Runners string `yaml:"runners"`
Name string `yaml:"name"`
Type string `yaml:"type"`
Command []Command
}
type Command struct {
Command string `yaml:"command"`
}
修改下面的代码以使其工作。
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var runContent = []byte(`
- runners:
- name: function1
type:
- command: spawn child process
- command: build
- command: gulp
- name: function1
type:
- command: run function 1
- name: function3
type:
- command: ruby build
- name: function4
type:
- command: go build
`)
type Runners []struct {
Runners []struct {
Type []struct {
Command string `yaml:"command"`
} `yaml:"type"`
Name string `yaml:"name"`
} `yaml:"runners"`
}
func main() {
runners := Runners{}
// parse mta yaml
err := yaml.Unmarshal(runContent, &runners)
if err != nil {
log.Fatalf("Error : %v", err)
}
fmt.Println(runners)
}
在此处在线验证您的 yaml https://codebeautify.org/yaml-validator/cb92c85b
- 1 回答
- 0 关注
- 240 浏览
添加回答
举报