Search code examples
goswitch-statementgoroutine

What is the difference between switch and select in Go?


Is there any difference between switch and select in Go,
apart from the fact that one takes an argument and the other not?


Solution

  • A select is only used with channels. Example

    A switch is used with concrete types. Example

    A select will choose multiple valid options at random, while aswitch will go in sequence (and would require a fallthrough to match multiple.)

    Note that a switch can also go over types for interfaces when used with the keyword .(type)

    var a interface{}
    a = 5
    switch a.(type) {
    case int:
         fmt.Println("an int.")
    case int32:
         fmt.Println("an int32.")
    }
    // in this case it will print "an int."