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

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.")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了