英文:
In golang, how to type assert an interface{} to a type specified by a reflect.Type?
问题
例如,我有一个名为a
的interface{}
,还有一个名为elemType
的reflect.Type
。现在,我想将a
类型断言为elemType
,但是a.(elemType)
无法成功编译。如何修复它?
抱歉我的表达有些混乱。我的意思是,我从一个函数中获取了一个类型,并且我想将interface{}
类型断言为这个类型,但是这个类型存储在一个reflect.Type
变量中。
我想要做的类似于下面的代码:
var a interface{}
//做一些操作
func getType() reflect.Type {
var ret reflect.Type
//做一些操作
return ret
}
targetType := getType()
result := a.(targetType)
英文:
For example, I have an interface{}
named a
, and I also have an reflect.Type
called elemType
. Now, I want to type assert a to elemType
, but a.(elemType)
can't be compiled successfully. How to fix it?
Sorry for my confusing expression. My meaning is that I get a type from a function, and I want to type assert an interface{} to this type, but this type is stored in a reflect.Type variable.
What I want to do is similar to the code below:
var a interface{}
//do something
func getType() reflect.Type {
var ret reflect.Type
//do something
return ret
}
targetType := getType()
result := a.(targetType)
答案1
得分: 2
考虑Go语言中的标准类型断言:
v := a.(typeName)
在这里,编译器可以在编译时确定变量v
的类型,并在编译涉及该变量的任何后续语句时利用这一知识。
对于你提到的在断言中使用reflect.Type
变量的示例,无法确定v
的类型,因此代码无法编译。
如果你需要在运行时检查特定接口变量是否为特定类型,仍然可以使用reflect
包来实现。例如:
// 如果elemType是一个普通类型
if reflect.ValueOf(a).Type() == elemType {
fmt.Println("类型匹配")
}
// 如果elemType是一个接口,可以检查值是否实现了该接口
if reflect.ValueOf(a).Type().Implements(elemType) {
fmt.Println("值实现了接口")
}
但是你需要一个具体类型来返回给标准变量。如果你只有一小部分可能的类型,也许使用类型切换(type switch)可以满足你的需求。
英文:
Consider a standard type assertion in Go:
v := a.(typeName)
Here the compiler can determine the type of the variable v
at compile time, and make use of that knowledge when compiling any further statements involving the variable.
With your example of using a refltect.Type
variable in the assertion, it would be impossible to determine the type of v
, so the code could not be compiled.
If you need to check that a particular interface variable is of a particular type at runtime, you can still do that with the reflect
package. For example:
// if elemType is a normal type
if reflect.ValueOf(a).Type() == elemType {
fmt.Println("type matches")
}
// if elemType is an interface, can check if the value implements it
if reflect.ValueOf(a).Type().Implements(elemType) {
fmt.Println("value implements interface")
}
But you will need a concrete type to return back to standard variables. If you've only got a small selection of possible types, perhaps using a type switch might do what you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论