Golang:动态地将接口​​转换为类型化变量 [英] Golang: cast an interface to a typed variable dynamically

查看:264
本文介绍了Golang:动态地将接口​​转换为类型化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,如果简单的转换是:

  var intAge = interfaceAge。(int)

如果我不知道这个年龄是否是一个整数?写一个简单的方法是

pre $ var $ x $ getType()
var someTypeAge = interfaceAge(.x)

有没有办法达到这样的效果?反射包提供了一些在运行时确定或转换类型的方法 - 但我找不到像上面提到的那样(一种适用于所有类型的通用方案)。

解决方案

不,你不能。 Go是一种静态类型语言。变量的类型是在编译时确定的。



如果要动态地确定类型 code> interface {} 您可以使用类型切换 a>:

  var t接口{} 
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(指向布尔%t \ n,* t的指针)// t有类型* bool
case * int:
fmt .Printf(指向整型%d \ n,* t)// t有类型* int
}


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).

解决方案

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 typeof 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
}

这篇关于Golang:动态地将接口​​转换为类型化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆