add an element to the end of an array in go

To add an element to the end of an array in Go, we can use slices. A slice is a dynamically sized, flexible view into the elements of an array. Here's an example:

main.go
package main

import "fmt"

func main() {
    // declare an array
    arr := [3]int{1, 2, 3}
    
    // create a slice using the array
    slice := arr[:]
    
    fmt.Println("Before:", slice)
    
    // append an element to the slice
    slice = append(slice, 4)
    
    fmt.Println("After:", slice)
}
307 chars
19 lines

In this example, we first declare an array arr with 3 elements. Then, we create a slice slice using the entire array [:], which creates a slice that includes all elements of the array. Finally, we use the append function to add a new element 4 to the end of the slice. The output of the program is:

main.go
Before: [1 2 3]
After: [1 2 3 4]
33 chars
3 lines

As you can see, the append function adds the new element to the end of the slice. Note that since the slice is a flexible view into the array, the original array arr is also updated with the new element.

related categories

gistlibby LogSnag