-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathswitch.go
More file actions
81 lines (63 loc) · 1.41 KB
/
Copy pathswitch.go
File metadata and controls
81 lines (63 loc) · 1.41 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
ann "github.com/benhalstead/gotraining/tutorial"
)
func main() {
//You can switch on any statement that evaluates to a value:
ann.Section("Switch on bool evaluation")
switch 1 == 2 {
case true:
fmt.Println("Unlikely")
case false:
fmt.Println("Expected")
default:
//Compiler won't catch impossible to reach default statements
}
//Most commonly you will test for a known value
ann.Section("Switch on known value")
a := 3
const SOME_CONST = 4
switch a {
case 3:
fmt.Println("Expected")
case SOME_CONST:
fmt.Println("Expected")
}
// But it is possible to have a case that matches based on another variable
ann.Section("Variable in case check ")
a = 2
b := 2
switch a {
case b:
fmt.Printf("%d == %d\n", a, b)
default:
fmt.Println("Unexpected")
}
// There is no concept of fallthrough in Go Switch statements - one or zero cases will match and be executed
ann.Section("No fall through")
a = 1
b = 1
c := 1
switch a {
case b:
case c:
fmt.Println("Will never be reached")
}
//Switch statements are an idiomatic way of handling variables where you don't know the type
ann.Section("Type switch")
var i interface{}
i = 1
switch t := i.(type) {
case int:
fmt.Println("Found an int")
case string:
fmt.Println("Found a string")
default:
// t is i 'cast' to the actual type
fmt.Printf("Value is %v\n", t)
}
}
func helper() bool {
return false
}