英文:
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
类型。
这种转换是否可能?
谢谢
英文:
I'm actually trying some black magic using reflection in golang
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
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论