dongyou6795
dongyou6795
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
default:
  // single object
}

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

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

1条回答

  • 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")
            default:
                fmt.Println("to unexpected type ", v.Elem().Kind())
            }
        }
    }
    

    https://play.golang.org/p/q32Cfz_dmF

    点赞 评论 复制链接分享

相关推荐