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

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?