Getting started with Go programming – Switch

The switch case does the same thing as it does in C but it differs in the following. Firstly

  • you don’t need to break at the end of each case.
  • There is no automatic fall through, you should specify it.
  • The expression can be  constants or integers  or any other.
  • handles multiple expression seperated by comma.
package main
import "fmt"

func main() {
 var input int
 fmt.Scanln(&input)

switch int(input) {
 case 1:
 fmt.Println("one")
 case 2:
 fmt.Println("two")
 case 3:
 fmt.Println("three")
 default:
 fmt.Println("Unhandled at this moment")
 }
}

The above code is a very simple example just similar to C , except that it does not have a break statement.

package main
import "fmt"

func main() {
var input int
fmt.Scanln(&input)

switch int(input) {
case 1:
fmt.Println("one")
fallthrough
case 2:
fmt.Println("two")
fallthrough
case 3:
fmt.Println("three")
fallthrough
default:
fmt.Println("Unhandled at this moment")
}
}

In case you need a fall through then its easy to get that by specifying fallthrough at the end of the case.


package main
import "fmt"

func main() {
var input int
fmt.Scanln(&input)

switch int(input) {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
case 4,5,6,7:
fmt.Println("Anytting between 4 to 7")
default:
fmt.Println("Unhandled at this moment")
}
}

In this example one of the case handles multiple expression seperated by comma.

package main
import "fmt"

func main() {
fmt.Println(typeName(1))
fmt.Println(typeName("1"))
}
func typeName(v interface{}) string {
switch v.(type) {
case int:
return "int"
case string:
return "string"
default:
return "unknown"
}
}

This type of switch is called type switch, It used to discover the dynamic type of an interface variable. We will cover interface in detail in the later post.

You can get the source code here – https://github.com/codelectron/GoLangSeries

Leave a Reply

Your email address will not be published. Required fields are marked *