Switch
This commit is contained in:
parent
0d55b2e490
commit
3712a36da9
1 changed files with 43 additions and 0 deletions
43
1flow/switch.go
Normal file
43
1flow/switch.go
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("Shorter way for lots of if else")
|
||||||
|
fmt.Println("No need to break after each statement")
|
||||||
|
fmt.Println("switch cases need not be constants, and the values involved need not be integers.")
|
||||||
|
|
||||||
|
os := runtime.GOOS
|
||||||
|
|
||||||
|
switch os {
|
||||||
|
case "windows":
|
||||||
|
fmt.Println("You are using windows")
|
||||||
|
case "linux":
|
||||||
|
fmt.Println("You are using linux")
|
||||||
|
default:
|
||||||
|
fmt.Printf("You are using %s\n", os)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
fmt.Println("Also you can add short statement before condition too")
|
||||||
|
// like: switch os := runtime.GOOS; os { . . . }
|
||||||
|
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
fmt.Println("You can use switch with no condition, this is same as `switch true`")
|
||||||
|
t := time.Now()
|
||||||
|
fmt.Println(t)
|
||||||
|
switch {
|
||||||
|
case t.Hour() < 12:
|
||||||
|
fmt.Println("Good morning!")
|
||||||
|
case t.Hour() < 17:
|
||||||
|
fmt.Println("Good afternoon.")
|
||||||
|
default:
|
||||||
|
fmt.Println("Good evening.")
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue