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.go307 chars19 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.go33 chars3 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.
gistlibby LogSnag