dseigqk7443 2011-06-16 13:13
浏览 108
已采纳

如何确定interface {}值的“真实”类型?

I have not found a good resource for using interface{} types. For example

package main

import "fmt"

func weirdFunc(i int) interface{} {
    if i == 0 {
        return "zero"
    }
    return i
}
func main() {
    var i = 5
    var w = weirdFunc(5)

    // this example works!
    if tmp, ok := w.(int); ok {
        i += tmp
    }

    fmt.Println("i =", i)
}

Do you know of a good introduction to using Go's interface{}?

specific questions:

  • how do I get the "real" Type of w?
  • is there any way to get the string representation of a type?
  • is there any way to use the string representation of a type to convert a value?
  • 写回答

6条回答 默认 最新

  • dqwh1208 2011-06-16 14:19
    关注

    Your example does work. Here's a simplified version.

    package main
    
    import "fmt"
    
    func weird(i int) interface{} {
        if i < 0 {
            return "negative"
        }
        return i
    }
    
    func main() {
        var i = 42
        if w, ok := weird(7).(int); ok {
            i += w
        }
        if w, ok := weird(-100).(int); ok {
            i += w
        }
        fmt.Println("i =", i)
    }
    
    Output:
    i = 49
    

    It uses Type assertions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失