英文:
How to cast an interface to a typed variable dynamically
问题
在Go语言中,是否有办法以某种方式动态地转换变量类型?
例如,如果简单的转换如下:
var intAge = interfaceAge.(int)
如果我事先不知道age是int类型,可以这样简单地编写:
var x = getType()
var someTypeAge = interfaceAge.(x)
是否有办法实现类似这样的功能?reflect包提供了一些在运行时确定或转换类型的方法,但我找不到类似上述的方法(一种适用于所有类型的通用方案)。
英文:
In Go, is it possible to cast variables dynamically somehow?
For example, if a simple cast would be:
var intAge = interfaceAge.(int)
What if I do not know that age is an int in advance? A simple way of writing it would be
var x = getType()
var someTypeAge = interfaceAge.(x)
Is there a way of achieving something like this? The reflect package gives some ways of determining or casting a type at runtime - but I couldn't find anything like the above mentioned (a generic scheme that would work for all types).
答案1
得分: 18
不,你不能。Go是一种静态类型语言,变量的类型在编译时确定。
如果你想动态确定interface{}
的type
,你可以使用type switching:
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T 打印出 t 的类型
case bool:
fmt.Printf("boolean %t\n", t) // t 的类型是 bool
case int:
fmt.Printf("integer %d\n", t) // t 的类型是 int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t 的类型是 *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t 的类型是 *int
}
英文:
No you can't. Go is a static typed language. The type of a variable is determined at compile time.
If you want to determine dynamically the type
of an interface{}
you could use type switching:
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论