Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluation sequence of `switch` in `go`

Tags:

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 ..."?

like image 394
Enze Chi Avatar asked Feb 08 '23 13:02

Enze Chi


1 Answers

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
like image 200
Amit Kumar Gupta Avatar answered Feb 11 '23 22:02

Amit Kumar Gupta