-
Notifications
You must be signed in to change notification settings - Fork 0
/
go_loop.go
86 lines (73 loc) · 1.64 KB
/
go_loop.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Module: go_loop.go
* Purpose: example GO loops, if, switch, etc. (flow control)
* Date: N/A
* Notes:
* 1) To build:
* go build go_loop.go
* 2) Ref: GO tutorial on flowcontrol
* https://tour.golang.org/flowcontrol
*
*/
package main
import "fmt"
// test function, called when main exits
func MyFunc(str string) {
fmt.Println(str)
}
// module main function
func main() {
// defered function, called when main exits
defer MyFunc("Deferred Bye call, goes on LIFO stack")
fmt.Println("go_loop: Go loops and loop notes\n");
// only loop type is for, parens not allowed, must use {}
var ii int
for ii=0; ii<3; ii++ {
fmt.Printf("II=%d\n", ii)
}
// using := will auto-define i below
for i:=0; i<3; i++ {
fmt.Printf("i=%d\n", i)
}
// for used like a while, note ;'s can be removed
// also note that inf loop can be written as "for {"
ii=0
for ii<10 {
ii++
// typical if statement, can include optional "("
if (ii==2) {
fmt.Println("We found 2")
}
if ii==3 {
fmt.Println("We found 3")
}
// if can include a pre-statement
if jj:=ii*2; ii==4 {
fmt.Printf("jj=%d\n", jj)
}
}
/* switch like C but implied "break" */
for xx:=1; xx<11; xx++ {
switch yy := xx*xx; yy {
case 1:
fmt.Println("One!")
case 4:
fmt.Println("Two squared")
case 9:
fmt.Println("Three squared and")
fallthrough // opposite of C's break....
default:
fmt.Printf("Many=%d,%d\n", xx, yy)
}
}
xx:=1
//yy:=2
// switch w/o condition is like switch true
// this is useful like multiple IF statements
switch {
case xx==1:
fmt.Println("XX is one!")
default:
fmt.Println("Should not get here")
}
}