@@ -6,7 +6,18 @@ import "fmt"
6
6
Range iterates over elements in a variety of data structures.
7
7
*/
8
8
func Run () {
9
+ // range over array & slice returns an index and the element.
9
10
rangeOverArray ()
11
+ rangeOverSlice ()
12
+
13
+ // range on a map returns both the key and value
14
+ rangeOverMap ()
15
+ // Range on strings returns the rune(s)
16
+ rangeOnStrings ()
17
+
18
+ // Range over channels. References the channels directory if they are a
19
+ // new concept to you!
20
+ rangeOverChannel ()
10
21
}
11
22
12
23
func rangeOverArray () {
@@ -17,3 +28,59 @@ func rangeOverArray() {
17
28
}
18
29
fmt .Println (total ) // 15
19
30
}
31
+
32
+ func rangeOverSlice () {
33
+ slice := []string {"one" , "two" }
34
+ for index , element := range slice {
35
+ fmt .Printf ("index: %d was %s\n " , index , element )
36
+ }
37
+ }
38
+
39
+ func rangeOverMap () {
40
+ m := map [string ]string {"one" : "One" , "two" : "Two" }
41
+ for key , value := range m {
42
+ fmt .Printf ("Key %s, Value %s\n " , key , value )
43
+ }
44
+ }
45
+
46
+ func rangeOnStrings () {
47
+ word := "hello"
48
+ for index , theRune := range word {
49
+ fmt .Println (index , theRune )
50
+ /*
51
+ The index of the characters, as well as the unicode code point for each one.
52
+ 0 104
53
+ 1 101
54
+ 2 108
55
+ 3 108
56
+ 4 111
57
+ */
58
+ }
59
+ }
60
+
61
+ func rangeOverChannel () {
62
+ /*
63
+ Note: if you are following in order, you aren't aware of channels yet but just take this
64
+ as-is for now, it likely won't make sense. Reference `channels` to understand more there
65
+ first
66
+ */
67
+
68
+ // This is a buffered channel, with a buffer size of 3
69
+ myChan := make (chan string , 3 )
70
+ // push three values in
71
+ myChan <- "one"
72
+ myChan <- "two"
73
+ myChan <- "three"
74
+
75
+ // Close the channel to signal, no more values will be sent
76
+ close (myChan )
77
+ for element := range myChan {
78
+ fmt .Println (element )
79
+ /*
80
+ "one"
81
+ "two"
82
+ "three"
83
+ */
84
+ }
85
+
86
+ }
0 commit comments