Hello everyone! Comeback with me, Indomieboy~
Today, I will explain a little bit about Switch on Golang.
-----------------------------------------------------------------------------------------------
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
In Go programming, switch are of two types:
- Expression Switch (I will use this)
- Type Switch
Expression Switch
The syntax for a Expression Switch statement in Go programming language is as follows:
switch(boolean-expression or integral type){ case boolean-expression or integral type : statement(s); case boolean-expression or integral type : statement(s); /* you can have any number of case statements */ default : /* Optional */ statement(s); }
Flow Diagram:
(image source: google)
Example:
package main
import "fmt"
func main() {
/* local variable definition */
var rank string = "2"
var marks int = 90
switch marks {
case 90: rank = "1"
case 80: rank = "2"
case 50,60,70 : rank = "3"
default: rank = "4"
}
switch {
case rank == "1" :
fmt.Printf("WOW! You are a champion!\n" )
case rank == "2", rank == "3" :
fmt.Printf("Well done\n" )
case rank == "4" :
fmt.Printf("Try again\n" )
case rank == "5":
fmt.Printf("Sorry you're loser\n" )
default:
fmt.Printf("Invalid rank\n" );
}
fmt.Printf("Your rank is %s\n", rank );
}
And this the result:
(image source: my screenshot)
--------------------------------------------------------------------------------------------------------------
Sorry if my grammar full of mistakes
#CMIIW
-----------------------------------------------------------------------------------------------------------------
Big thank's for Google & many blogger



0 komentar:
Posting Komentar