forked from mkaz/working-with-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06-for-loops.go
51 lines (40 loc) · 995 Bytes
/
06-for-loops.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
/**
* for-loops.go
* Go uses "for" for all loops, there is no "while" or "do-while" loops
*
*/
package main
import "fmt"
func main() {
// creating an array of strings
alphas := []string{"abc", "def", "ghi"}
// standard for loop
for i := 0; i < len(alphas); i++ {
fmt.Printf("%d: %s \n", i, alphas[i])
}
// if iterating over a array, this would be how you would actually do it
// the standard loop would be used if uncommon step function
// range returns two values, i -> index, val -> value
for i, val := range alphas {
fmt.Printf("%d: %s \n", i, val)
}
// if you did not care about the value and only wanted the index
for i := range alphas {
fmt.Println(i)
}
// if you did not care about the index and only the value, you use the _
// which means don't save this value
for _, val := range alphas {
fmt.Println(val)
}
// how to use for like a while
x := 0
for x < 10 {
fmt.Println(x)
x++
}
// infinite loop
// for {
// fmt.Print(".")
// }
}