假设我有一个基本结构,它是另外两个的组合:
type Config struct {
common.Config
common.ServerConfig
APIPath string `type:"string" name:"apipath" default:"localhost:8443" desc:"Path to the gRPC API server"`
ServePath string `type:"string" name:"servepath" default:"/" desc:"Path to serve the API from"`
Organization string `type:"string" name:"organization" default:"" desc:"Default organization name"`
}
我想遍历结构中的每个字段并将值拉入结构:
func NewConfig(c Configer) {
setConfigflags(reflect.TypeOf(c).Elem(),c.GetViper())
}
所以我这样称呼:
conf := Config{}
common.NewConfig(&conf)
我的setConfigflags正在做一些递归:
func setConfigflags(t reflect.Type,viper *viper.Viper) {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
switch field.Type.Kind() {
case reflect.Struct:
setConfigflags(field.Type,viper)
continue
case reflect.String:
fieldValue := reflect.ValueOf(&field).Elem()
if !fieldValue.IsValid() || !fieldValue.CanSet() {
return
}
fieldValue.SetString(
viper.GetString(field.Tag.Get("name")),)
}
}
}
现在,一旦我朝底部点击SetString行,我就会收到此错误:
panic: reflect: call of reflect.Value.SetString on struct Value
当我查看那时的fieldValue类型时,它是一个structfield。我在尝试解决该值并更改字段的值时遇到了麻烦。我相信我没有正确地获取实际struct字段的地址。这些示例和文档肯定没有帮助。
在此特定示例中,我提取了毒蛇值。基本上是寻找一种通过struct标签定义毒蛇定义的方法,这才是最终目标。