gpt4 book ai didi

reflection - 在 Go 中获取空结构 slice 的字段

转载 作者:数据小太阳 更新时间:2023-10-29 03:33:23 26 4
gpt4 key购买 nike

我有一个函数

func (r *render) foo(v interface{}) {
val := reflect.ValueOf(v)
fields := structs.Fields(val.Index(0).Interface())

...

它接受一片结构并尝试获取 v 的字段,但是,如果 v 为空,则“val.Index(0)”会使程序崩溃。有更好的方法吗?

最佳答案

你需要先检查你是否有一个 slice 开始,然后检查你是否有一个空 slice ,你可能应该检查你是否也有一个结构:(example)

val := reflect.ValueOf(v)
if val.Kind() != reflect.Slice {
fmt.Println("not a slice")
return
}

if val.Len() == 0 {
fmt.Println("empty slice")
return
}

if val.Index(0).Kind() != reflect.Struct {
fmt.Println("not a slice of structs")
return
}

fields := structs.Fields(val.Index(0).Interface())
...

如果你只想要结构类型中的字段,不管 slice 是否为空,你都可以使用 slice 类型的Elem方法来提取它(example)

// get the internal type of the slice
t := val.Type().Elem()
if t.Kind() != reflect.Struct {
fmt.Println("not a struct")
return
}

fmt.Println("Type:", t)
for i := 0; i < t.NumField(); i++ {
fmt.Println(t.Field(i).Name)
}

关于reflection - 在 Go 中获取空结构 slice 的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924199/

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