我想要以下 yaml
kind: bar name: baryaml
在結構體 resource 中解組
type kind int const ( kind_foo kind = iota kind_bar ) type resource struct { kind kind name string }
有人可以解釋為什麼下面的程式碼無法儲存正確的類型,即使它被正確解組了嗎?
# output: unmarshaled kind: 1 yamlbar: {0 baryaml}
# expected output: unmarshaled kind: 1 yamlbar: {1 baryaml}
package main import ( "fmt" "gopkg.in/yaml.v3" ) type Kind int const ( KIND_FOO Kind = iota KIND_BAR ) func (k *Kind) UnmarshalYAML(value *yaml.Node) error { var kind string err := value.Decode(&kind) if err != nil { return err } var x Kind switch kind { case "foo": x = KIND_FOO case "bar": x = KIND_BAR default: return fmt.Errorf("unknown kind: %s", kind) } k = &x fmt.Println("Unmarshaled kind:", *k) return nil } type Resource struct { Kind Kind Name string } func main() { var yamlBar = ` kind: bar name: baryaml ` r := Resource{} err := yaml.Unmarshal([]byte(yamlBar), &r) if err != nil { panic(err) } fmt.Println("yamlBar:", r) }
感謝@jimb 建議取消引用 k
指標:
func (k *Kind) UnmarshalYAML(value *yaml.Node) error { var kind string err := value.Decode(&kind) if err != nil { return err } switch kind { case "foo": *k = KIND_FOO case "bar": *k = KIND_BAR default: return fmt.Errorf("unknown kind: %s", kind) } fmt.Println("Unmarshaled kind:", *k) return nil }
以上是如何從 golang 中的 yaml 解組結構內的型別別名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!