go select and switch statement

tags: learning go programming diff-between

content

syntax

select:

go func() {
	select {
	case i := <-chInt
		fmt.Println(i)
	case c := <-chString
		fmt.Println(c)
	}
}()

switch:

func main() {
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("macOS.")
	case "linux":
		fmt.Println("Linux.")
	default:
		fmt.Printf("%s.\n", os)
	}
}

function

  • switch is just another way to do if-else
  • select lets go routine to wait on multiple communication operation
    • communication operation: channel is one of them
    • select is blocked when none of the case is matched
    • select picks a random one when multiple communication is ready

up

down

reference