How to add items to Slice using append function in Golang?
To add an item to the end of the slice, use the append() method.
Example
package main
import "fmt"
func main() {
a := make([]int, 2, 5)
a[0] = 10
a[1] = 20
fmt.Println("Slice A:", a)
fmt.Printf("Length is %d Capacity is %d\n", len(a), cap(a))
a = append(a, 30, 40, 50, 60, 70, 80, 90)
fmt.Println("Slice A after appending data:", a)
fmt.Printf("Length is %d Capacity is %d\n", len(a), cap(a))
}
Output
Slice A: [10 20]
Length is 2 Capacity is 5
Slice A after appending data: [10 20 30 40 50 60 70 80 90]
Length is 9 Capacity is 12
If there's sufficient capacity in the underlying slice, the element is placed after the last element and the length get incremented. However, if there is not sufficient capacity, a new slice is created, all of the existing elements are copied over, the new element is added onto the end, and the new slice is returned.
Most Helpful This Week
Golang program for implementation of Radix Sort
Golang program for implementation of Insertion Sort
How do you write multi-line strings in Go?
Convert Int data type to Int16 Int32 Int64
GO language program with example of String Compare function
How do you create an HTTP server in Go?
GO Program to take user input and addition of two strings
React JS Count number of checkboxes are checked
Golang program for implementation of Levenshtein distance
Illustration of the dining philosophers problem in Golang