add an item to an array in go

To add an item to an array in Go, you would need to create a slice from the array, append the new item to the slice, and then create a new array from the updated slice. Here is an example:

main.go
package main

import "fmt"

func main() {
    // create an array with 3 elements
    arr := [3]int{1, 2, 3}

    // convert the array to a slice
    slice := arr[:]

    // append a new element to the slice
    slice = append(slice, 4)

    // create a new array from the updated slice
    newArr := [4]int{}
    copy(newArr[:], slice)

    fmt.Println(newArr) // prints [1 2 3 4]
}
383 chars
21 lines

In this example, we first create an array with 3 elements. We then convert the array to a slice using the [:] notation. We then append a new element to the slice using the append() function. Finally, we create a new array with a length of 4 and copy the updated slice into it using the copy() function. The resulting array contains all of the original elements plus the new element we added.

related categories

gistlibby LogSnag