Golang: Append to Slice
Append to Slice
The append
is a critical function in golang.
It's used to append, prepend, join, slices, or delete elements in slice.
You need to pay attention whether it returns a new slice or just modify the original.
append(slice_x, newItem1, newItem2, etc)
-
Append new items to a slice, returns a new slice only if the result is more than the original slice's capacity.
🛑 WARNING: if the original slice is a slice of slice, then result may not go beyond its capacity, therefore, the result shares data as original slice. Meaning, change to the result also changes original slice.
Example: Basic Append
package main import "fmt" func main() { var s1 = []int{3, 5} var s2 = append(s1, 8, 9) fmt.Println(s2) // [3 5 8 9] // original not changed, in this case fmt.Println(s1) // [3 5] }
Example: Append May or May Not Share Original Slice Data
Append creates a new slice ONLY WHEN the result is beyond original capacity.
package main import "fmt" func main() { var x1 = []int{0, 1, 2, 3, 4, 5} var x2 = x1[:3] // [0 1 2] var x3 = append(x2, 22) fmt.Println(x3) // [0 1 2 22] // x1 is changed fmt.Println(x1) // [0 1 2 22 4 5] // -------------------------------------------------- // if the append added more items than the capacity of x1, then x1 will not be changed // now we do the above again to see var y1 = []int{0, 1, 2, 3, 4, 5} var y2 = y1[:3] // [0 1 2] var y3 = append(y2, 21, 22, 23, 24, 25) fmt.Println(y3) // [0 1 2 21 22 23 24 25] // y1 is not changed fmt.Println(y1) // [0 1 2 3 4 5] }
Join Slices
Use triple dots operator to turn a slice into function arguments,
then use append
.
append(slice_x, slice_y ...)
package main import "fmt" func main() { var s1 = []int{3, 5} var s2 = []int{6, 7} var s3 = append(s1, s2...) fmt.Println(s3) // [3 5 6 7] }
Append String as Byte Slice to Slice
Use triple dots operator to turn a string into byte slice,
then use append
.
append(slice_x, string ...)
Golang, array and slice
- Golang: Array
- Golang: Slice
- Golang: Slice of Slice
- Golang: Append to Slice
- Golang: Cut Slice (Delete Elements)
- Golang: Copy Slice
- Golang: Clear Slice
- Golang: Nested Slice
- Golang: Slice of Strings to String
- Golang: Iterate Slice
- Golang: Convert Value to String
- Golang: Convert Array to Slice
- Golang: Print Slice, Array