Appending to and copying slices in Golang

Slices are a powerful feature of Go that allow you to work with dynamic arrays. One of the advantages of using slices is that they can be easily appended to and copied.

Appending to a slice in Go is done using the built-in append function. The append function takes a slice and one or more elements and returns a new slice with the elements appended to it. If the original slice has enough capacity to hold the new elements, the append function will reuse the underlying array. If not, a new array will be allocated.

Here is an example of appending to a slice in Go:

package main

import “fmt”

func main() {
s := []int{1, 2, 3}
s = append(s, 4, 5, 6)
fmt.Println(s) // Output: [1 2 3 4 5 6]}

This code initializes a slice s with three integers and then appends three more integers to it using the append function. The output of the program will be [1 2 3 4 5 6].

Copying a slice in Go is done using the built-in copy function. The copy function takes two slices and copies the elements from the source slice to the destination slice. If the destination slice has a smaller capacity than the source slice, the copy function will only copy as many elements as can fit in the destination slice.

Here is an example of copying a slice in Go:

package main

import “fmt”

func main() {
s1 := []int{1, 2, 3}
s2 := make([]int, len(s1))
copy(s2, s1)
fmt.Println(s2) // Output: [1 2 3]}

This code initializes a slice s1 with three integers, creates a new slice s2 with the same length as s1, and then copies the elements from s1 to s2 using the copy function. The output of the program will be [1 2 3].

Practice Questions on Appending to and Copying Slices in Golang

Here are some practice questions on appending to and copying slices in Go:

What is the built-in function in Go for appending to a slice?

A. insert
B. append
C. add
D. concat

Answer: B

What happens if the original slice does not have enough capacity to hold the new elements when using the append function in Go?

A. The new elements are discarded
B. A new array is allocated and the new elements are appended to it
C. The program crashes
D. The original slice is expanded to fit the new elements

Answer: B

What is the built-in function in Go for copying one slice to another?

A. clone
B. copy
C. duplicate
D. replicate

Answer: B

What happens if the destination slice has a smaller capacity than the source slice when using the copy function in Go?

A. The program crashes
B. The function returns an error
C. Only as many elements as can fit in the destination slice are copied
D. The function does not copy any elements

Answer: C

Allocation in Golang
Arithmetic operators in Golang

Get industry recognized certification – Contact us

keyboard_arrow_up