登录
首页 >  Golang >  Go问答

为什么在使用 Golang yaml.v2 时,我的结构体被转换为映射?

来源:stackoverflow

时间:2024-03-19 20:24:31 418浏览 收藏

使用 Golang 的 yaml.v2 库时,在将结构体传递给 `yaml.Unmarshal` 函数时可能会遇到问题。当使用反射创建结构体并传递其接口时,该结构体会被转换为映射。这是因为反射创建的结构体实际上是 `interface{}` 类型,而不是预期的结构体类型。为了解决此问题,需要在传递之前将结构体转换为其实际类型。可以通过使用 `reflect.ValueOf(base).Elem().Interface().(testconf)` 来实现,其中 `testconf` 是预期的结构体类型。

问题内容

我正在开发一个通用配置解析器,它读取 yaml 配置文件并将结果存储在结构中。我希望解析器与类型无关,并且我想实现一些覆盖逻辑,所以我使用反射。

下面是我正在处理的完整但非常简化的版本,它说明了对 yaml.unmarshal 调用的问题。如果我传入一个指向我在没有反射的情况下创建的结构的指针(示例代码中的 base2 := testconf{} ),它会按预期工作:一个强类型结构进入,一个强类型结构出来。

但是,如果我传入一个使用反射创建的结构(示例代码中的 base := reflect.new(configtype).elem().interface() ),我会传入一个结构并获得一个 map [接口{}]接口{} 返回。正如您所看到的,我已尽力验证这两个结构是否相同,如果它们的类型不同或不是 deepequal,则会出现恐慌。

目前这让我很头疼,但我可以解决它。我只是想了解为什么会发生这种情况,也许还可以了解解决方法。

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "reflect"
    "time"

    yaml "gopkg.in/yaml.v2"
)

type testconf struct {
    requiredconfig `yaml:"requiredconfig"`
    str1           string     `yaml:"str1"`
    strptr1        *string    `yaml:"strptr1"`
    timeptr        *time.time `yaml:"timeptr"`
}

type requiredconfig struct {
    environment string `yaml:"environment"`
}

var baseconfigpath = "./config_test.yml"

func main() {
    conf := testconf{}
    loadconfig(&conf)
}

func loadconfig(target interface{}) {
    targetactual := reflect.valueof(target).elem()
    configtype := targetactual.type()
    base := reflect.new(configtype).elem().interface()
    base2 := testconf{}

    if reflect.typeof(base) != reflect.typeof(base2) {
        panic("your argument is invalid")
    }

    if !reflect.deepequal(base, base2) {
        panic("your argument is invalid")
    }

    if _, err := os.stat(baseconfigpath); !os.isnotexist(err) {
        raw, _ := ioutil.readfile(baseconfigpath)

        fmt.printf("before base type: \"%v\", kind: \"%v\"\n", reflect.typeof(base), reflect.valueof(base).kind())
        err = yaml.unmarshal(raw, &base)
        fmt.printf("after base type: \"%v\", kind: \"%v\"\n", reflect.typeof(base), reflect.valueof(base).kind())

        fmt.printf("before base2 type: \"%v\", kind: \"%v\"\n", reflect.typeof(base2), reflect.valueof(base2).kind())
        err = yaml.unmarshal(raw, &base2)
        fmt.printf("after base2 type: \"%v\", kind: \"%v\"\n", reflect.typeof(base2), reflect.valueof(base2).kind())
    }
}

要运行此程序,您还需要将此 yaml 文件保存在 ./config_test.yml

requiredconfig:
  environment: dev
str1: string 1
strptr1: string pointer 1
timeptr: 2018-08-01t17:25:50.179949-04:00

我得到的输出:

Before base Type: "main.TestConf", Kind: "struct"
After base Type: "map[interface {}]interface {}", Kind: "map"
Before base2 Type: "main.TestConf", Kind: "struct"
After base2 Type: "main.TestConf", Kind: "struct"

因此 base2 的行为符合预期。 base 以某种方式转换为地图。


解决方案


那是因为这一行:

base := reflect.new(configtype).elem().interface()

此时实际上是类型interface{}。

如果你这样做:

base, ok := base := reflect.new(configtype).elem().interface().(testconf)
if !ok{
    panic("got wrong type")
}
//rest of your code

您将得到您期望的结果。

编辑回复地址

传递指针接口umarshal

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "reflect"
    "time"

    yaml "gopkg.in/yaml.v2"
)

type testconf struct {
    requiredconfig `yaml:"requiredconfig"`
    str1           string     `yaml:"str1"`
    strptr1        *string    `yaml:"strptr1"`
    timeptr        *time.time `yaml:"timeptr"`
}

type requiredconfig struct {
    environment string `yaml:"environment"`
}

var baseconfigpath = "./config_test.yml"

func main() {
    conf := testconf{}
    loadconfig(&conf)
}

func loadconfig(target interface{}) {
    targetactual := reflect.valueof(target).elem()
    configtype := targetactual.type()
    basereflect := reflect.new(configtype)
    // actual type.
    base := basereflect.elem().interface()
    base2 := testconf{}

    if reflect.typeof(base) != reflect.typeof(base2) {
        panic("your argument is invalid")
    }

    if !reflect.deepequal(base, base2) {
        panic("your argument is invalid")
    }

    if _, err := os.stat(baseconfigpath); !os.isnotexist(err) {
        raw, _ := ioutil.readfile(baseconfigpath)

        fmt.printf("before base type: \"%v\", kind: \"%v\"\n", reflect.typeof(base), reflect.valueof(base).kind())
        // passes the pointer to unmarshal
        err = yaml.unmarshal(raw, basereflect.interface())
        fmt.printf("after base type: \"%v\", kind: \"%v\"\n", reflect.typeof(base), reflect.valueof(base).kind())

        fmt.printf("before base2 type: \"%v\", kind: \"%v\"\n", reflect.typeof(base2), reflect.valueof(base2).kind())
        err = yaml.unmarshal(raw, &base2)
        fmt.printf("after base2 type: \"%v\", kind: \"%v\"\n", reflect.typeof(base2), reflect.valueof(base2).kind())
    }
}

产量:

Before base Type: "main.TestConf", Kind: "struct"
After base Type: "main.TestConf", Kind: "struct"
Before base2 Type: "main.TestConf", Kind: "struct"
After base2 Type: "main.TestConf", Kind: "struct"

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《为什么在使用 Golang yaml.v2 时,我的结构体被转换为映射?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>