Home  >  Article  >  Backend Development  >  How to unmarshal type alias inside struct from yaml in golang?

How to unmarshal type alias inside struct from yaml in golang?

王林
王林forward
2024-02-06 08:57:08616browse

如何从 golang 中的 yaml 中解组结构内的类型别名?

Question content

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)
}


Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:ent-go o2m upsert copyNext article:ent-go o2m upsert copy