-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic1.go
71 lines (61 loc) 路 1.31 KB
/
basic1.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
package main
import "fmt"
func main() {
fmt.Println("---basic syntax---")
// 1. if
var num = 1
if num > 1 {
fmt.Println("greater than 1")
} else if num < 1 {
fmt.Println("less than 1")
} else {
fmt.Println("equals to 1")
}
// if multiple conditions
// In Go, := is for declaration + assignment, whereas = is for assignment only.
// For example, var foo int = 10 is the same as foo := 10.
if v := num - 100; v < 0 {
fmt.Println("v is less than 0")
}
// 2. switch
counter := 100
switch counter {
case 99:
fmt.Println("less than 100")
case 100:
fmt.Println("equals to 100")
fallthrough // fall through to next switch case
case 101:
selfPrint()
default:
fmt.Println("fall back to this line")
}
// 3. for - Go only has for loop
var sum int = 0
for i := 0; i < 10; i++ {
sum += i
}
println(sum) // 45 - 0 ~ 9
// Go does not support while keyword, we can use the following case if needed
for sum < 100 {
sum += sum
}
println(sum) // 180
// infinite loop
for {
sum++
println("current sum", sum)
if sum == 190 {
println("sum equals to 190")
break
}
}
// 4. for-range
// iterate over array, string, map, object etc
for index, char := range []string{"first", "second", "third"} {
println(index, char)
}
}
func selfPrint() {
fmt.Println("---greater than 100---")
}