duanche4578
2019-02-24 16:27
浏览 476
已采纳

Golang类型断言以指向切片

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duange2971 2019-02-24 16:46
    已采纳

    [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.")
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题