【问题标题】:Golang type assertion for pointer to slice指向切片的指针的 Golang 类型断言
【发布时间】:2019-07-18 03:16:02
【问题描述】:

有没有更好的方法?

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
}

play.golang.org 上的完整示例

【问题讨论】:

  • 没有反射是不可能的,不是吗?
  • 如果你知道什么类型的切片,你可以使用类型断言而不是反射,但是如果有任何类型的切片,那么不,不是没有反射。
  • 好的,我不知道具体的类型。谢谢!

标签: go type-assertion


【解决方案1】:

[本回答原文由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.")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 2021-09-15
    • 1970-01-01
    • 2016-08-01
    • 2017-08-11
    • 2015-05-01
    • 2016-12-28
    • 1970-01-01
    相关资源
    最近更新 更多