Open In App

Golang Program that uses String Switch

With the help of switch case we can implement the functionality of as many if statements. In Golang, switch cases can work with strings, list of variables including integer values as well as floating values.

Syntax:

switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..

default: Statement..
}

Example 1:

In this example we can see that by using switch cases and assuming variable as a string type we can make use of switch cases.

// Golang program that uses string switch 
package main 

// Here "fmt" is formatted IO which 
// is same as C’s printf and scanf. 
import "fmt"

// Main function 
func main() { 
    day := "Tue"

    // Use switch on the day variable. 
    switch { 
    case day == "Mon": 
        fmt.Println("Monday") 
    case day == "Tue": 
        fmt.Println("Tuesday") 
    case day == "Wed": 
        fmt.Println("Wednesday") 
    } 
} 

Output :

Tuesday

Example 2:

// Golang program that uses string switch 
package main 

// Here "fmt" is formatted IO which 
// is same as C’s printf and scanf. 
import "fmt"

// Main function 
func main() { 
    gfg := "Geek"

    // Use switch on the gfg variable. 
    switch { 
    case gfg == "Geek": 
        fmt.Println("Geek") 
    case gfg == "For": 
        fmt.Println("For") 
    case gfg == "Geeks": 
        fmt.Println("Geeks") 
    } 
} 

Output:

Geek
Article Tags :