在 Go 中获取空结构切片的字段

Get fields of empty struct slice in Go

我有一个功能

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

...

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

你需要先检查你是否有一个切片开始,然后检查你是否有一个空切片,你可能应该检查你是否也有一个结构:(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())
...

如果您只想要结构体 type 中的字段,无论切片是否为空,您都可以使用切片类型的 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)
}