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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵