Skip to content

Commit 4f1cbae

Browse files
committed
Added more examples of slices like creating slices using the make function, appending to slices
1 parent a4a501f commit 4f1cbae

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

go_basics/data_structures/data_structures.go

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,23 @@ func learnDynamicArrays() {
9595

9696
printSlice(dummySlice)
9797

98+
// Creating a slice with make
99+
100+
fmt.Println("Creating slices with make, lets see the length and capacity")
101+
102+
// assigns a length of 5
103+
newSlice := make([]int, 5)
104+
105+
printSlice(newSlice)
106+
107+
// assigns a capacity of 5
108+
newSlice = make([]int, 0, 5)
109+
110+
newSlice = newSlice[:cap(newSlice)]
111+
newSlice = newSlice[0:3]
112+
113+
printSlice(newSlice)
114+
98115
}
99116

100117
func createSlicesOfSlices() {
@@ -123,7 +140,30 @@ func createSlicesOfSlices() {
123140
}
124141
}
125142

126-
func printSlice[T []int](val T) {
143+
func appendThingsToSlices() {
144+
fmt.Println("This is appending someting to slices")
145+
146+
someArray := [5]string{
147+
"Aniket",
148+
"Animesh",
149+
"Ankush",
150+
"Ankit",
151+
"Amaan",
152+
}
153+
154+
someSlice := make([]string, 0)
155+
156+
for i := 0; i < len(someArray); i++ {
157+
someSlice = append(someSlice, someArray[i])
158+
}
159+
160+
someSlice = append(someSlice, "Adding name: Amitava")
161+
fmt.Println("Slice after appending")
162+
fmt.Println(someSlice)
163+
printSlice(someSlice)
164+
}
165+
166+
func printSlice[T []int | []string](val T) {
127167
fmt.Printf("\n len = %v, cap = %v \n", len(val), cap(val))
128168
}
129169

@@ -136,5 +176,11 @@ func main() {
136176

137177
learnDynamicArrays()
138178

179+
// create 2D arrays
180+
139181
createSlicesOfSlices()
182+
183+
// appendThingsToSlices
184+
185+
appendThingsToSlices()
140186
}

0 commit comments

Comments
 (0)