I want the following yaml
kind: bar name: baryaml
Unmarshalling in structure resource
type kind int const ( kind_foo kind = iota kind_bar ) type resource struct { kind kind name string }
Can someone explain why the code below fails to store the correct type, even though it is unmarshalled correctly?
# 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) }
Thanks to @jimb for suggesting dereferencing k
Pointer:
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 }
The above is the detailed content of How to unmarshal type alias inside struct from yaml in golang?. For more information, please follow other related articles on the PHP Chinese website!