Skip to content

Commit 9c158ee

Browse files
committed
Added range function in loops and a new 2D slice assessment in data_structures.go
1 parent 4f1cbae commit 9c158ee

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

go_basics/data_structures/data_structures.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,35 @@ func printSlice[T []int | []string](val T) {
167167
fmt.Printf("\n len = %v, cap = %v \n", len(val), cap(val))
168168
}
169169

170+
/*
171+
It should return
172+
173+
a slice of length dy inside of which each element will be a slice of length dx
174+
175+
*/
176+
177+
func Pic(dx, dy int) [][]byte {
178+
picture := make([][]byte, dy)
179+
180+
for row := 0; row < dy; row++ {
181+
picture[row] = make([]byte, dx)
182+
for column := 0; column < dx; column++ {
183+
fmt.Println("row and column is", row, column)
184+
picture[row][column] = byte((row + column) / 2)
185+
}
186+
}
187+
return picture
188+
}
189+
190+
func sliceExerice() {
191+
fmt.Println("recovered", recover())
192+
pic := Pic(6, 3)
193+
194+
for i := 0; i < len(pic); i++ {
195+
fmt.Println(pic[i])
196+
}
197+
}
198+
170199
func main() {
171200

172201
// learn arrays
@@ -183,4 +212,8 @@ func main() {
183212
// appendThingsToSlices
184213

185214
appendThingsToSlices()
215+
216+
// exercise
217+
218+
sliceExerice()
186219
}

go_basics/loops/loops.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,25 @@ func getNonInitAndPostForLoop() {
5050

5151
}
5252

53+
// range is a short form of an iterator used to iterate maps, sets, slices
54+
func getRangeFormOfLoops() {
55+
56+
primeNumbers := []int{
57+
1,
58+
2,
59+
3,
60+
5,
61+
7,
62+
11,
63+
13,
64+
}
65+
66+
// we can skip index, value by using _ as the underlying value
67+
for idx, value := range primeNumbers {
68+
fmt.Printf("{index, value} = {%v, %v} ", idx, value)
69+
}
70+
}
71+
5372
func main() {
5473

5574
// simple for loop
@@ -67,4 +86,7 @@ func main() {
6786
6887
}
6988
*/
89+
90+
// get Range form loops
91+
getRangeFormOfLoops()
7092
}

0 commit comments

Comments
 (0)