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

I have a function

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

...

Which takes a slice of structs and tries to get the fields of v, however if v is empty then "val.Index(0)" crashes the program. Is there a better way to do this?

You need to check first if you have a slice to begin with, then check if you have an empty slice, and you probably should check that you have a struct too while you're at it: (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())
...

If you only want the fields from a struct type, regardless of if the slice is empty, you can use the slice type's Elem method to extract it (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)
}