如何将接口动态转换为具体类型的变量?

huangapple go评论88阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2015年1月16日 03:55:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/27971895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定