gpt4 book ai didi

go - 接口(interface)内反射阵列

转载 作者:IT王子 更新时间:2023-10-29 02:31:07 25 4
gpt4 key购买 nike

我正在尝试通过反射访问接口(interface)中的数组。

在其他字段中,我还有一个字符串数组:

type Configuration struct {
...
SysVars []string
}

我可以像这样访问字段SysVars:

elem := reflect.ValueOf(conf).Elem()
sysVarsInterface := elem.FieldByName("SysVars").Interface()

至此,当使用 GoLand 的调试器时,我可以看到 sysVarsInterface 是一个具有我期望的两个值的接口(interface)。由于它是一个数组,我假设我需要将它视为接口(interface)并再次反射(reflect)它?所以它看起来像这样:

sysVarsValue := reflect.ValueOf(&sysVarsInterface)
sysVarsElem := sysVarsValue.Elem()

但是遍历它失败了:

for i:=0; i< sysVarsElem.NumField(); i++ {
vname := sysVarsElem.Type().Field(i).Name
fmt.Println(vname)
}

说:

panic: reflect: call of reflect.Value.NumField on interface Value

任何想法我做错了什么?
我用的是this作为引用

最佳答案

无需双重反射,您可以像这样迭代 SysVars :

p := &Configuration{
SysVars :[]string{"a","b","c"},
}

s:= reflect.ValueOf(p).Elem().FieldByName("SysVars")
for i:=0 ; i< s.Len() ; i++ {
fmt.Println(s.Index(i).String())
}

关于go - 接口(interface)内反射阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915203/

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