To add an item to a slice in Go, we can use the built-in function append
. The syntax is as follows:
main.go32 chars2 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.go253 chars15 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.
gistlibby LogSnag