gpt4 book ai didi

reflection - Reflect.Value.FieldByName 导致 panic

转载 作者:IT老高 更新时间:2023-10-28 13:10:09 29 4
gpt4 key购买 nike

调用反射值的 .FieldByName 方法时出现以下错误,确切的错误是:-

panic: reflect: call of reflect.Value.FieldByName on ptr Value

代码是:-

s := reflect.ValueOf(&value).Elem() (value is a struct)
metric := s.FieldByName(subval.Metric).Interface() (subval.Metric is a string)

我知道这并不多,但这是我能得到的所有信息。

这是 Go Playground 上代码的链接:http://play.golang.org/p/E038cPOoGp

最佳答案

你的 value 已经是一个指向结构的指针。尝试在您的代码中打印出 s.Kind()

没有理由获取 value 的地址,然后在该 reflect.Value 上调用 Elem(),这会取消引用您的指针刚刚创建。

s := reflect.ValueOf(value).Elem()
metric := s.FieldByName(subvalMetric).Interface()
fmt.Println(metric)

关于reflection - Reflect.Value.FieldByName 导致 panic ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537525/

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