如何通过反射中的 reflect.New 创建的类型来转换为 reflect.Value?

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

How to cast a reflect.Value by its type when created by reflect.New

问题

我正在尝试在golang中使用反射进行一些黑魔法:P

我得到了类似这样的代码:

  var _int int
  var _int32 int32
  var _int64 int64
  var _string string

  var nilablesIndex map[int]reflect.Value
  var nilables = map[string]reflect.Type {
         "int32":     reflect.TypeOf(_int32),
         "int64":     reflect.TypeOf(_int64),
         "int":       reflect.TypeOf(_int),
         "string":    reflect.TypeOf(_string),
      }
  nilablesIndex[len(m) - 1] = reflect.New(nilables[field.Type.String()][1])

总结一下,我现在有一个通过reflect.New(nilables[field.Type.String()][1])创建的reflect.Value变量。

我想要的是按照它的原始类型对这个变量进行类型转换。

例如:如果nilablesIndex[0]是一个reflect.Type int32,我想将它转换为int32类型。

这种转换是否可能?

谢谢 如何通过反射中的 reflect.New 创建的类型来转换为 reflect.Value?

英文:

I'm actually trying some black magic using reflection in golang 如何通过反射中的 reflect.New 创建的类型来转换为 reflect.Value?

I got something like this :

  var _int int
  var _int32 int32
  var _int64 int64
  var _string string

    var nilablesIndex map[int]reflect.Value
    var nilables = map[string]reflect.Type {
           "int32":     reflect.TypeOf(_int32)},
           "int64":     reflect.TypeOf(_int64)},
           "int":       reflect.TypeOf(_int)},
           "string":    reflect.TypeOf(_string)},
        }
nilablesIndex[len(m) - 1] = reflect.New(nilables[field.Type.String()][1])

To summarize, I have at this moment a reflect.Value created by reflect.New(nilables[field.Type.String()][1])

That I want is to cast this variable by its original type.

Example : If nilablesIndex[0] is a reflect.Type int32, I want to cast it to type int32.

Is it possible ?

Thank you 如何通过反射中的 reflect.New 创建的类型来转换为 reflect.Value?

答案1

得分: 1

你无法使其动态化,因为实际上你正在转换为一个具体的类型(如果结果是动态的,那么它的类型会是什么?interface{}?你又回到了起点)。

你可以使用Value.Interface()type assertion

例如:

var i int32 = 3

v := reflect.ValueOf(i)

x := v.Interface().(int32)
fmt.Printf("%T %v", x, x)

输出结果(在Go Playground上尝试):

int32 3
英文:

You can't make it dynamic, because you are actually converting to a concrete type (what would be the type of the result if it would be dynamic? interface{}? you'd be back at the start).

You may use Value.Interface() and a type assertion.

For example:

var i int32 = 3

v := reflect.ValueOf(i)

x := v.Interface().(int32)
fmt.Printf("%T %v", x, x)

Output (try it on the Go Playground):

int32 3

huangapple
  • 本文由 发表于 2017年6月12日 17:37:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/44496132.html
匿名

发表评论

匿名网友

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

确定