如何从指向单个对象的指针解析为指向数组的指针

huangapple go评论123阅读模式
英文:

How reslove pointer to array from pointer to single object

问题

我尝试在我的程序中找到一种解决方法,以便在特定函数中使用interface{}作为参数,来区分指向数组的指针和指向单个对象的指针。目前我使用以下方式得到了结果:

  1. func object(v interface{}) {
  2. if strings.HasPrefix(reflect.TypeOf(v).String(), "*[]") {
  3. // 指向数组的指针
  4. } else {
  5. // 指向单个对象的指针
  6. }
  7. }

上述方法可以工作,但对我来说不是很清晰的代码。我认为可以使用Golang的类型和反射包来更好地解决这个问题,但我现在不知道如何做,请您给予建议。

附注:我不想使用switch语句,例如:

  1. switch v.(type) {
  2. case *[]someType:
  3. // 数组
  4. default:
  5. // 单个对象
  6. }

这种方法应该更通用,不依赖于数组对象的具体类型。

英文:

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:

  1. func object( v interface{}) {
  2. if strings.HasPrefix(reflect.TypeOf(v).String(), "*[]") {
  3. // pointer to array
  4. } else {
  5. // pointer to single object
  6. }
  7. }

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:

  1. switch v.(type){
  2. case *[]someType:
  3. // array
  4. default:
  5. // single object
  6. }

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

答案1

得分: 2

使用reflect.Kind来检查你所拥有的值的类型:

  1. func object(i interface{}) {
  2. v := reflect.ValueOf(i)
  3. switch v.Kind() {
  4. case reflect.Ptr:
  5. fmt.Print("我们有一个指针 ")
  6. switch v.Elem().Kind() {
  7. case reflect.Slice:
  8. fmt.Println("指向一个切片")
  9. case reflect.Array:
  10. fmt.Println("指向一个数组")
  11. case reflect.Struct:
  12. fmt.Println("指向一个结构体")
  13. default:
  14. fmt.Println("指向一个意外的类型", v.Elem().Kind())
  15. }
  16. }
  17. }

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

英文:

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

  1. func object(i interface{}) {
  2. v := reflect.ValueOf(i)
  3. switch v.Kind() {
  4. case reflect.Ptr:
  5. fmt.Print("we have a pointer ")
  6. switch v.Elem().Kind() {
  7. case reflect.Slice:
  8. fmt.Println("to a slice")
  9. case reflect.Array:
  10. fmt.Println("to an array")
  11. case reflect.Struct:
  12. fmt.Println("to a struct")
  13. default:
  14. fmt.Println("to unexpected type ", v.Elem().Kind())
  15. }
  16. }
  17. }

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

huangapple
  • 本文由 发表于 2016年12月2日 06:17:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/40921407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定