duanmei2805 2017-10-30 12:08
浏览 37
已采纳

通过字符串名称将类型转换为特定的结构类型

I would like to typecast a specific variable to a specific defined struct/interface by using the string name value of the struct/interface.

For example:

type Testing interface{}

and new variable

stringName := "Testing"
newTestingVariable.(stringName)

Is this possible by chance? Perhaps using reflection?

Cheers

  • 写回答

1条回答 默认 最新

  • dqkelut8423 2017-10-30 12:24
    关注

    It is not possible. Go is a statically typed language, which means types of variables and expressions must be known at compile-time.

    In a type assertion:

    x.(T)
    

    [...] If the type assertion holds, the value of the expression is the value stored in x and its type is T.

    So you use type assertion to get (or test for) a value of a type you specify.

    When you would do:

    stringName := "Testing"
    newTestingVariable.(stringName)
    

    What would be the type of the result of the type assertion? You didn't tell. You specified a string value containing the type name, but this can only be decided at runtime. (Yes, in the above example the compiler could track the value as it is given as a constant value, but in the general case this is not possible at compile time.)

    So at compile time the compiler could only use interface{} as the type of the result of the type expression, but then what's the point?

    If the point would be to dynamically test if x's type is T (or that if the interface value x implements T), you can use reflection for that (package reflect). In this case you would use a reflect.Type to specify the type to be tested, instead of a string representation of its name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题