Enze Chi
Enze Chi

Reputation: 1763

evaluation sequence of `switch` in `go`

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

Answers (1)

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 18607

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

Upvotes: 9

Related Questions