In this guide, we will look at using the append function to add values to a slice. Since a slice does not have a dynamic size, it removes or adds values.
Golang Append Function
The append method in go allows you to add any number of specified items to the end of a slice.
If the underlying array contains enough capacity, go use this array. Otherwise, if there is not enough capacity to hold the specified elements, go creates a new underlying array and copies the existing data (including the new values) to the new array.
The function syntax can be expressed as:
The function takes the name of the slice to append to and the element(s) to append to the slice as the arguments.
The function will return a slice with the original values and the new ones appended to the slice.
Keep in mind that the append function does not affect the slice in-place. It only returns an updated slice with the specified “changes”. Hence, you may need to save the return value into a variable.
Append to Slice
Consider the example below that appends new values to a slice.
import "fmt"
func main() {
my_slice := []string{"James", "Marlon", "Winnie", "Wesly"}
fmt.Println(my_slice)
my_slice = append(my_slice, "Jane", "Maya")
fmt.Println(my_slice)
}
The append function will take the specified elements and add them to the my_slice slice.
The resulting output is as shown:
[James Marlon Winnie Wesly Jane Maya]
You can also append elements to an empty slice, as shown in the example below:
import "fmt"
func main() {
my_slice := []string{}
fmt.Println(my_slice)
my_slice = append(my_slice, "Jane", "Maya")
fmt.Println(my_slice)
}
The resulting slice:
[]
[Jane Maya]
Append Slice to Slice
You can also append the elements of a slice to another slice using the three-dot operator. Yes, like JavaScript.
Consider the example below:
my_slice := []string{"Orange", "Apple", "Banana"}
another_slice := []string{"Tomato", "Strawberry", "Melon"}
my_slice = append(my_slice, another_slice...)
fmt.Println(my_slice)
}
The function above takes one slice and appends it to the other slice. Pay attention to the three-dot after the second slice (parameter).
This tells the function to unpack the elements of the slice and append them to the new slice. An example output:
Otherwise, the append operation fails.
The compiler returns an error as:
Append String to Byte Slice
You can also append a string to a byte slice as shown below:
byte_slice := make([]byte, 0)
byte_slice = append(byte_slice, []byte("Linuxhint")...)
fmt.Println(byte_slice)
}
Similar to appending a slice to a slice, we need to unpack the string to bytes. A resulting byte slice is as shown:
Conclusion
In this guide, we covered various techniques of using the append method in the go programming language. Using this method, you can add new elements to slices with ease.