show me switch/case in golang in go

In Go, the switch statement can be used as an alternative to writing a series of if-else statements. It provides a concise and clean way to perform multiple condition checks.

Here's an example of a switch statement in Go:

main.go
package main

import (
	"fmt"
)

func main() {
	grade := 90

	switch {
	case grade >= 90 && grade <= 100:
		fmt.Println("A")
	case grade >= 80 && grade < 90:
		fmt.Println("B")
	case grade >= 70 && grade < 80:
		fmt.Println("C")
	case grade >= 60 && grade < 70:
		fmt.Println("D")
	default:
		fmt.Println("F")
	}
}
315 chars
23 lines

In this example, we have a variable grade with a value of 90. Inside the switch statement, we check the value of grade against different conditions using case statements. The switch statement evaluates each case condition sequentially until a match is found. If no match is found, the default case is executed.

In this case, since the value of grade is between 90 and 100, the first case condition is true, so the output will be A.

related categories

gistlibby LogSnag