英文:
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 othercase
blocks match - the
default
block can be anywhere within theswitch
block, and not necessarily last in lexical order
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论