英文:
Replace viper map key without replacing entire map
问题
我正在使用viper进行配置。如何在不替换整个映射的情况下替换一个键?
package main
import (
"log"
"github.com/spf13/viper"
)
type person struct {
First string
Last string
}
func main() {
v := viper.New()
v.SetEnvPrefix("mememe")
v.AutomaticEnv()
bob := person{
First: "Bob",
Last: "Smith",
}
john := person{
First: "John",
Last: "Boothe",
}
v.SetDefault("people.bob", bob)
v.SetDefault("people.john", john)
log.Println(v.Get("people")) // map[bob:{Bob Smith} john:{John Boothe}]
bob.Last = "Hope"
v.Set("people.bob", bob)
log.Println(v.Get("people")) // map[bob:{Bob Hope}]
}
在设置新的Bob时,我完全丢失了John。如果我将"SetDefault"更改为简单的"Set",似乎可以工作,但我想知道为什么"SetDefault"不起作用。
英文:
I am using viper for my config. How do I replace a key without replacing the entire map?
package main
import (
"log"
"github.com/spf13/viper"
)
type person struct {
First string
Last string
}
func main() {
v := viper.New()
v.SetEnvPrefix("mememe")
v.AutomaticEnv()
bob := person{
First: "Bob",
Last: "Smith",
}
john := person{
First: "John",
Last: "Boothe",
}
v.SetDefault("people.bob", bob)
v.SetDefault("people.john", john)
log.Println(v.Get("people")) // map[bob:{Bob Smith} john:{John Boothe}]
bob.Last = "Hope"
v.Set("people.bob", bob)
log.Println(v.Get("people")) // map[bob:{Bob Hope}]
}
Upon setting the new Bob I lose John completely. If I change "SetDefault" to simply "Set" then it seems to work but I am wondering why "SetDefault" doesn't work.
答案1
得分: 0
我猜是因为这个原因,来自于访问嵌套键的文档。
然而,如果datastore.metric被一个立即值(通过标志、环境变量、Set()方法等)覆盖,那么datastore.metric的所有子键将变为未定义,它们被更高优先级的配置级别“遮蔽”。
所以一旦设置了people.bob
,people
就会存在,并且people.*
不再被视为未填充。
我不知道如何解决这个问题。
英文:
I'm going to guess it's because of this, from the docs on Accessing nested keys.
> However, if datastore.metric was overridden (by a flag, an environment variable, the Set() method, …) with an immediate value, then all sub-keys of datastore.metric become undefined, they are “shadowed” by the higher-priority configuration level.
So as soon as people.bob
is set, people
springs into existence and people.*
are no longer considered unpopulated.
I don't know how to work around it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论