Reputation: 1
I'm actually trying some black magic using reflection in golang :P
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 :)
Upvotes: 0
Views: 5623
Reputation: 417462
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
Upvotes: 1