-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09_switch.go
65 lines (55 loc) · 1.52 KB
/
09_switch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//Desicion making. Branching with switch.
package main
import "fmt"
func main() {
// More complex decision making
// Shorter verion of if - else
// Cases evaluated top to bottom, first matching case is selected
// No automatic fall through, instead keyword 'fallthrough' can be used
// Switching on an expression
switch "match" {
case "match":
fmt.Println("Matched!")
case "noMatch":
fmt.Println("This branch will not execute")
default:
// If no above cases match, default branch is used
fmt.Println("Defaulted!")
}
// Switching with no condition, the same as switch true
// Instead 'case' branches are evaluated based on 'truthfulness', top to bottom
// Idiomatic way of writing if-else-if-else chains
var myFavouriteFruit = "banana"
switch {
case myFavouriteFruit == "ketchup":
fmt.Println("Blahhhhh!")
case myFavouriteFruit == "banana":
fmt.Println("They're so easy to peel!")
default:
// If no above cases match, default branch is used
fmt.Println("Defaulted!")
}
//Task: Check the current time, and accordingly print out
//Good morning, Good afternoon or Good evening.
//Use time package and Now().
// Falling through!
switch {
case true:
fmt.Println("This one mathces!")
fallthrough
case true:
fmt.Println("Even this one mathces!")
fallthrough
case false:
fmt.Println("Yes, even this is selected.")
}
//Cases can be presented in comma-separated lists.
fmt.Println(escape('?'))
}
func escape(c byte) bool {
switch c {
case ' ', '?', '&', '=', '#', '+':
return true
}
return false
}