切片指针的 Golang 类型断言

Golang type assertion for pointer to slice

有更好的方法吗?

var collection []string
anyFunc(&collection) // valid
anyFunc(collection) // invalid
anyFunc(nil) // invalid
anyFunc("test") // invalid

func anyFunc(collection interface{}) error {
    rv := reflect.ValueOf(collection)
    if rv.Kind() != reflect.Ptr || rv.IsNil() || reflect.Indirect(reflect.ValueOf(collection)).Kind() != reflect.Slice {
        return errors.New("Invalid collection type, need pointer to slice.")
    }
    return nil
}

完整示例位于 play.golang.org

[本回答文字由mkopriva原创]

func loadData(collection interface{}) error {
    rv := reflect.ValueOf(collection)
    if rv.Kind() == reflect.Ptr && rv.Elem().Kind() == reflect.Slice {
        return nil  
    }
    return errors.New("Invalid collection type, need pointer to slice.")
}