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 關注
- 207 瀏覽
添加回答
舉報