Reputation: 1763
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 ..."?
Upvotes: 5
Views: 1694
Reputation: 18607
From this Golang tutorial:
default
is executed if none of the other case
blocks matchdefault
block can be anywhere within the switch
block, and not necessarily last in lexical orderUpvotes: 9