doue8385 2019-05-10 18:05
浏览 44
已采纳

为什么在Go类型开关中声明了一个单独的变量?

I am having trouble understanding why type switches are written with an additional variable defined in the switch statement. The below code seems to be the sanctioned way of doing things:

func test_func(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("%T
", v)
    case float64:
        fmt.Printf("%T
", v)
    case int:
        fmt.Printf("I don't know about type %T!
", v)
    }
}

func main() {
    test_func(float64(34))
    test_func(int(34))
    test_func("hello world")
}

As expected, this returns:

float64
int
I don't know about type string!

However, I can change test_func slightly so that v is not defined in the switch statement, and instead we use i inside our case statements:

func test_func(i interface{}) {
    switch i.(type) {
    case int:
        fmt.Printf("%T
", i)
    case float64:
        fmt.Printf("%T
", i)
    case int:
        fmt.Printf("I don't know about type %T!
", i)
    }
}

func main() {
    test_func(float64(34))
    test_func(int(34))
    test_func("hello world")
}

And the output is not changed. It seems the two forms are interchangeable. Why would I go to the trouble of defining v when I could just use i? The latter case is simpler since there is one less variable to keep track of; maybe it is even more performant.

  • 写回答

1条回答 默认 最新

  • duanjiati1755 2019-05-10 18:10
    关注

    They are not interchangeable; you're just passing i to a function that can take it regardless of its type (fmt.Printf's arguments after the format string are of type interface{}). i is still its original type, because the type of a variable cannot change.

    If you actually wanted to do something with it based on its type, you would need the first form, so that v would be of the type in the case statement. Whether or not you assign the typed value to a variable, the original variable i retains its original type.

    This is covered well in the Tour of Go: Type switches

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向