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

王林
Release: 2024-02-06 08:57:08
forward
619 people have browsed it

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

Question content

I want the following yaml

kind: bar
name: baryaml
Copy after login

Unmarshalling in structure resource

type kind int

const (
    kind_foo kind = iota
    kind_bar
)

type resource struct {
    kind kind
    name string
}
Copy after login

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}
Copy after login
# expected output:
unmarshaled kind: 1
yamlbar: {1 baryaml}
Copy after login
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)
}

Copy after login


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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template