【问题标题】:Why is a separate variable declared in a Go type switch?为什么在 Go 类型开关中声明一个单独的变量?
【发布时间】:2019-09-28 16:01:19
【问题描述】:

我无法理解为什么使用 switch 语句中定义的附加变量来编写类型开关。下面的代码似乎是被认可的做事方式:

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

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

正如预期的那样,这会返回:

float64
int
I don't know about type string!

但是,我可以稍微更改test_func,以便v 不在switch 语句中定义,而是在我们的case 语句中使用i

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

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

并且输出没有改变。这两种形式似乎可以互换。当我可以使用i 时,为什么还要麻烦定义v?后一种情况更简单,因为要跟踪的变量更少;也许它的性能更高。

【问题讨论】:

标签: go types switch-statement declaration definition


【解决方案1】:

它们不可互换;您只是将i 传递给一个无论其类型如何都可以接受它的函数(格式字符串后的fmt.Printf 的参数是interface{} 类型)。 i 仍然是它原来的类型,因为变量的类型不能改变

如果你真的想根据它的类型对它做一些事情,你需要第一种形式,这样v 就是case 语句中的类型。无论您是否将类型化的值分配给变量,原始变量i 都会保留其原始类型。

Tour of Go: Type switches 对此进行了很好的介绍

【讨论】:

  • 啊,我明白了。我对fmt.Printf 中的%T 不打印interface{},而是接口封装的类型这一事实感到困惑。对于开发人员而言,这似乎是一个奇怪的决定。感谢您的帮助!
  • 如果没有,它会总是打印interface{},无论你传入什么,因为这是接收所有参数的类型。
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多