add an item to an array of type int in go

To add an item to an existing array in golang, we have to make use of the built-in append function. Here is an example:

main.go
package main

import "fmt"

func main() {
    // create an array of type int with 3 elements
    arr := [3]int{1, 2, 3}
    fmt.Println("Original Array:", arr)
    
    // add an element at the end of the array using append
    arr = append(arr, 4)
    
    fmt.Println("New Array:", arr)
}
291 chars
15 lines

Output:

main.go
Original Array: [1 2 3]
New Array: [1 2 3 4]
45 chars
3 lines

In the above code snippet, we first create an array arr of type int with 3 elements. We then use the append function to add an element 4 at the end of the array. Note that the append function returns a new slice, which we then assign to the original array arr so that it now contains the new element.

related categories

gistlibby LogSnag