[英]Golang type assertion for pointer to slice
Is there a better way for that?有没有更好的方法?
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
}
Full example at play.golang.org play.golang.org 上的完整示例
[The text of this answer was originally written by mkopriva ] 【本回答原文由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.")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.