2016-12-01 22:17



I try in my porogram find way to resolve beetwen type pointer to array form pointer to single object using interface{} as argument in particular function. On this time i get this reslut using below way:

func object( v interface{}) {
    if strings.HasPrefix(reflect.TypeOf(v).String(), "*[]") {
        // pointer to array 
    } else {
        //  pointer to single object

Above way works, but for me this is not clean code. I think that exist some better way to solve this using golang package as type, reflect but now I don't no how so please Your suggestion.

Ps. I don't want to use switch statemet for example:

switch v.(type){
case *[]someType:
  // array
  // single object

This should be more universal does not depend on the type object of array

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dtz88967 dtz88967 5年前

    Use the reflect.Kind to check the kind of value you have:

    func object(i interface{}) {
        v := reflect.ValueOf(i)
        switch v.Kind() {
        case reflect.Ptr:
            fmt.Print("we have a pointer ")
            switch v.Elem().Kind() {
            case reflect.Slice:
                fmt.Println("to a slice")
            case reflect.Array:
                fmt.Println("to an array")
            case reflect.Struct:
                fmt.Println("to a struct")
                fmt.Println("to unexpected type ", v.Elem().Kind())

    点赞 评论 复制链接分享