英文:
unexported field or method for go interface
问题
我对Go语言还不太熟悉,但是我可以帮你翻译代码和错误信息。以下是翻译的结果:
我对Go语言还不太熟悉,我正在尝试循环遍历接口的每个字段(可以是不同的结构体),但是我不确定以下代码出了什么问题?它报告了运行时错误:panic: reflect.Value.Interface: 无法返回从未导出的字段或方法获取的值。
那些未导出的字段/方法是什么?我将SomeField字段大写了,谢谢。
type SomeStruct struct {
SomeField uint32
}
func test(obj interface{}) {
typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
for i := 0; i < typ.NumField(); i++ {
fieldValue := val.Field(i).Interface()
fmt.Println(fieldValue)
}
}
func test1(obj interface{}) {
val := reflect.ValueOf(obj)
test(val)
}
func main() {
var ss SomeStruct
test1(ss)
}
希望这可以帮到你!如果你有其他问题,请随时问。
英文:
I am quite new to go, and I am trying to loop through each field of an interface (can be different struct) but I am not sure what is going wrong with the following code? it reports runtime error: panic: reflect.Value.Interface: cannot return value obtained from unexported field or method
what are those unexported field/method? I have the SomeField field capitalized thanks
type SomeStruct struct {
SomeField uint32
}
func test(obj interface{}){
typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
for i := 0; i < typ.NumField(); i++ {
fieldValue := val.Field(i).Interface()
fmt.Println(fieldValue)
}
}
func test1(obj interface{}){
val := reflect.ValueOf(obj)
test(val)
}
func main() {
var ss SomeStruct
test1(ss)
}
答案1
得分: 5
在Go语言中,结构体中以小写字母开头的字段表示其作用域为私有,而以大写字母开头的字段表示公共。因此,你应该将字段以大写字母开头。
英文:
in Go struct,field started in lowercase means its scope is private,while uppercase means public. So,you should keep the field started with UpperCase alpha.
答案2
得分: 2
我认为你只是想运行这段代码:
package main
import "fmt"
import "reflect"
type SomeStruct struct {
SomeField uint32
}
func test(obj interface{}) {
typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
for i := 0; i < typ.NumField(); i++ {
fieldValue := val.Field(i).Interface()
fmt.Println(fieldValue)
}
}
func main() {
var ss SomeStruct
test(ss)
ss.SomeField = 1
test(ss)
}
你原始的代码尝试获取val := reflect.ValueOf(ss)
的每个字段的值,而不是ss
的值。
英文:
I think you just wanted to run this:
package main
import "fmt"
import "reflect"
type SomeStruct struct {
SomeField uint32
}
func test(obj interface{}){
typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
for i := 0; i < typ.NumField(); i++ {
fieldValue := val.Field(i).Interface()
fmt.Println(fieldValue)
}
}
func main() {
var ss SomeStruct
test(ss)
ss.SomeField = 1
test(ss)
}
Your original code tries to get a value of each field of val := reflect.ValueOf(ss)
instead of ss
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论