evaluation sequence of `switch` in `go`

huangapple go评论76阅读模式
英文:

evaluation sequence of `switch` in `go`

问题

我正在学习Go语言,通过阅读《Effective Go》。我发现了一个关于类型切换的例子:

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T\n", t)     // %T 打印出 t 的实际类型
case bool:
    fmt.Printf("boolean %t\n", t)             // t 的类型是 bool
case int:
    fmt.Printf("integer %d\n", t)             // t 的类型是 int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t 的类型是 *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t 的类型是 *int
}

我的理解是,在switch语句中,case从上到下依次进行匹配,直到找到匹配的条件为止。所以,这个例子不是总是会停在default并打印"unexpected type ..."吗?

英文:

I am learning Go language by reading "Effective Go".

I found a example about type switch:

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T\n", t)     // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}

My understanding is the cases in switch is evaluated from top to bottom and stop at a match condition. So isn't the example about would always stop at default and print "unexpected type ..."?

答案1

得分: 8

这个Golang教程中:

  • 如果没有其他case块匹配,将执行default的代码块。
  • default块可以位于switch块的任何位置,不一定是按词法顺序的最后一个。
英文:

From this Golang tutorial:

  • The code block of default is executed if none of the other case blocks match
  • the default block can be anywhere within the switch block, and not necessarily last in lexical order

huangapple
  • 本文由 发表于 2015年11月16日 06:30:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/33725883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定