Search code examples
gotype-assertion

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


Solution

  • [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.")
    }