Switch in golang
package main
import (
"fmt"
)
func main() {
var num int = 2
switch num {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
default:
fmt.Println("Other")
}
}
Explanation:
package main
: Declares that this file is part of the main package.import "fmt"
: Imports the "fmt" package, which provides functions for formatting text and printing to the console.func main() { ... }
: Defines the main function, the entry point of the program.var num int = 2
: Declares a variablenum
of typeint
and initializes it with the value2
.switch num { ... }
: Starts a switch statement based on the value of the variablenum
.case 1:
: Checks ifnum
is equal to1
.fmt.Println("One")
: Ifnum
is1
, it prints "One" to the console.case 2:
: Checks ifnum
is equal to2
.fmt.Println("Two")
: Ifnum
is2
, it prints "Two" to the console.case 3:
: Checks ifnum
is equal to3
.fmt.Println("Three")
: Ifnum
is3
, it prints "Three" to the console.default:
: Ifnum
doesn't match any of the cases, this block is executed.fmt.Println("Other")
: Prints "Other" to the console in the default case.