douji5397
2015-01-15 19:55
浏览 182
已采纳

Golang:将接口动态转换为类型变量

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

图片转代码服务由CSDN问答提供 功能建议

在进行中,是否可以通过某种方式动态地转换变量?

对于 例如,如果简单的强制转换为:

  var intAge = interfaceAge。(int)
   
 
 

如果 我不知道年龄是预先整数吗? 一种简单的编写方式是

  var x = getType()
var someTypeAge = interfaceAge(.x)
   
 \  n 

有没有办法实现这样的目标? 反射包提供了一些在运行时确定或强制转换类型的方法-但我找不到像上述提到的东西(适用于所有类型的通用方案)。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmufen8105 2015-01-15 20:17
    已采纳

    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
    ", t)             // t has type bool
    case int:
        fmt.Printf("integer %d
    ", t)             // t has type int
    case *bool:
        fmt.Printf("pointer to boolean %t
    ", *t) // t has type *bool
    case *int:
        fmt.Printf("pointer to integer %d
    ", *t) // t has type *int
    }
    
    点赞 评论

相关推荐 更多相似问题