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

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

报告相同问题?

悬赏问题

  • ¥20 R语言单细胞测序 对seurat对象进行标准化时出现问题
  • ¥15 Anaconda navigator updateor一直更新
  • ¥15 请问如何在matlab里使用raven工具?
  • ¥100 关于ios手游充值到一定金额,再点充值提示公众号的问题。
  • ¥15 求一个stm32串口控制程序
  • ¥20 Windows 驱动开发版本疑问相关
  • ¥15 MAC 未能打开磁盘映像
  • ¥15 fastcap使用,二维导体输入问题
  • ¥15 hosts修改后不能访问
  • ¥15 关于化学反应速率C++编译问题/FLUENT