Skip to content

Commit 26b3395

Browse files
committed
adding documentation around range and a slight reference to channels
1 parent 2bd4470 commit 26b3395

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ all the examples `Run` functions sequentially in line with the table of contents
2222
* [08 - Arrays](arrays/main.go)
2323
* [09 - Slices](slices/main.go)
2424
* [10 - Maps](maps/main.go)
25+
* [11 - Range](ranges/main.go)

ranges/main.go

+67
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,18 @@ import "fmt"
66
Range iterates over elements in a variety of data structures.
77
*/
88
func Run() {
9+
// range over array & slice returns an index and the element.
910
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()
1021
}
1122

1223
func rangeOverArray() {
@@ -17,3 +28,59 @@ func rangeOverArray() {
1728
}
1829
fmt.Println(total) // 15
1930
}
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

Comments
 (0)