Skip to content
Advertisements

Golang: Switch-case does not fall through!

Unlike C/C++ switch-case statements, Golang switch case does not fall through.

package main
import (
	"fmt"
)

func main() {
	fmt.Print("Go runs on ")
	os := "darwin"
	switch os {
	case "darwin":
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

The above code does not print anything!

package main
import (
	"fmt"
)

func main() {
	fmt.Print("Go runs on ")
	os := "darwin"
	switch os {
	case "darwin":
	fallthrough
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

You have to add fallthrough statement to make it work. The above code prints Linux.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: