简体   繁体   中英

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

[The text of this answer was originally written by 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.")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM