我想要以下 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中文网其他相关文章!