gpt4 book ai didi

go - 如何使用 viper 加载 map 列表?

转载 作者:IT王子 更新时间:2023-10-29 00:58:01 25 4
gpt4 key购买 nike

我有以下配置要用 viper 加载:

artist:
name: The Beatles
albums:
- name: The White Album
year: 1968
- name: Abbey Road
year: 1969

我不知道如何加载 map 列表。我想我只需要解码这个 key ,但这段代码不起作用:

type Album struct {
Name string
Year int
}

type Artist struct {
Name string
Albums []Album
}

var artist Artist
viper.UnmarshalKey("artists", &artist)

我错过了什么?

最佳答案

你确定 yaml 中的键是 artists 吗?您的意思是提供 artist 吗?

工作示例:

str := []byte(`artist:
name: The Beatles
albums:
- name: The White Album
year: 1968
- name: Abbey Road
year: 1969
`)

viper.SetConfigType("yaml")
viper.ReadConfig(bytes.NewBuffer(str))

var artist Artist
err := viper.UnmarshalKey("artist", &artist)

fmt.Printf("%v, %#v\n", err, artist)

输出:

<nil>, main.Artist{Name:"The Beatles", Albums:[]main.Album{main.Album{Name:"The White Album", Year:1968}, main.Album{Name:"Abbey Road", Year:1969}}}

关于go - 如何使用 viper 加载 map 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com