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 variable num of type int and initializes it with the value 2.
  • switch num { ... }: Starts a switch statement based on the value of the variable num.
  • case 1:: Checks if num is equal to 1.
  • fmt.Println("One"): If num is 1, it prints "One" to the console.
  • case 2:: Checks if num is equal to 2.
  • fmt.Println("Two"): If num is 2, it prints "Two" to the console.
  • case 3:: Checks if num is equal to 3.
  • fmt.Println("Three"): If num is 3, it prints "Three" to the console.
  • default:: If num doesn't match any of the cases, this block is executed.
  • fmt.Println("Other"): Prints "Other" to the console in the default case.