add an item to a slice in go

To add an item to a slice in Go, we can use the built-in function append. The syntax is as follows:

main.go
newSlice := append(slice, item)
32 chars
2 lines

Here, slice is the original slice to which the item has to be added, and item is the element to be appended. The append function returns a new slice, which includes the original slice and the newly appended item.

For example, consider the code below:

main.go
package main

import "fmt"

func main() {
    // create a slice of integers
    nums := []int{1, 2, 3, 4, 5}

    // add a new item to the slice
    nums = append(nums, 6)

    // print the updated slice
    fmt.Println(nums) // Output: [1 2 3 4 5 6]
}
253 chars
15 lines

In the above example, we first create a slice of integers nums with 5 elements. Then, we use the append function to add a new element 6 to the slice. Finally, we print the updated slice which includes the newly added element.

related categories

gistlibby LogSnag