英文:
golang cast to relfect.Type
问题
我的问题如下:
我有一个reflect.Value
的切片,它是从MethodByName("foo").Call()
返回的。
现在我想将其中的值转换为它们的类型,但我不知道静态类型,只知道reflect.Type
的形式。
基本上我想做的是:
values[0].Interface().(mytype)
但是使用反射:
values[0].Interface().(reflect.TypeOf(responseObject))
这给我带来了编译错误:
reflect.TypeOf(responseObject)不是一个类型
在Go语言中有没有办法做到这一点?
谢谢和问候
BillDoor
英文:
My Problem is as follows:
I have a slice of reflect.Value
, that was returned from a MethodByName("foo").Call()
.
now i want to cast the contained values to their types, which i dont know statically, but in form of relflect.Type
Basically what i want to do is:
values[0].Interface().(mytype)
but with reflection
values[0].Interface().(reflect.TypeOf(responseObject))
This gives me the compilation error:
reflect.TypeOf(responseObject) is not a type
Is there a way to do this in go?
Thanks and regards
BillDoor
答案1
得分: 4
如果你使用普通的类型断言语法,例如:
x := v.(mytype)
那么编译器会知道变量 x
的类型是 mytype
,并相应地生成代码。如果语言允许你在类型的位置使用表达式,那么编译器将无法知道变量 x
的类型,因此也无法生成使用该变量的代码。
如果你只在运行时知道值的类型,那么你需要使用 reflect.Value
API。你可以使用其 Type
方法确定值的类型,并且还有一些方法可以让你访问结构体字段、切片或数组中的索引等。
只有在编译时知道类型时,你才能回到常规的语法。
英文:
If you have code using the normal type assertion syntax like:
x := v.(mytype)
Then the compiler knows that the variable x
is of type mytype
, and generates code accordingly. If the language let you use an expression in place of the type, then the compiler would have no way of knowing what type x
is, and consequently no way to generate code that uses that variable.
If you only know the type of value at runtime, then you will need to stick with the reflect.Value
API. You can determine the value's type using its Type
method, and there are methods that will let you access struct fields, indexes in slices or arrays, etc.
You will only be able to move back to regular syntax when you have a type you know about at compile time.
答案2
得分: 1
什么是类型断言(cast)?它有两个效果:
- 在编译时,整个类型断言表达式的编译时类型是被转换的类型。
- 在运行时,会检查值的实际运行时类型,如果不是被转换的类型,就会生成一个运行时错误。
显然,对于在编译时不知道的类型,第一点是没有意义的,因为在编译时如何将某物的编译时类型依赖于在编译时不知道的东西呢?
对于在编译时不知道的类型,你仍然可以手动执行第二点。只需使用reflect.TypeOf()
获取值的运行时类型,并将其与你拥有的runtime.Type
进行比较。
英文:
What is a cast (type assertion)? It has two effects:
- At compile time, the compile-time of the whole type assertion expression is the type casted to.
- At runtime, a check is made on the actual runtime type of the value, and if it is not the type casted to, it will generate a runtime error.
Obviously, #1 doesn't make sense for a type that is not known at compile-time, because how can the compile-time type of something depend on something not known at compile time?
You can still do manually do #2 for a type that is not known at compile time. Just get the runtime type of the value using reflect.TypeOf()
and compare it against the runtime.Type
you have.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论