Copy slices in Go

0
35
Copy slices in Go
Copy slices in Go

You wonder how to clone slices in Go, I will show you how to use a builtin function to copy slices in Go.

The builtin function in Go that helps us to clone or copy slices is copy().

// The copy built-in function copies elements from a source slice into a
// destination slice. (As a special case, it also will copy bytes from a
// string to a slice of bytes.) The source and destination may overlap. Copy
// returns the number of elements copied, which will be the minimum of
// len(src) and len(dst).
func copy(dst, src []Type) int

Return value is the number of copied elements. Why? As you can see from the description of the function, it is actually the minimum number between size of source slice and size of destination slice.

To illustrate, please see following code:

func srcSizeIsLessThanDestSize() {
   src := []int{1, 2, 3, 4, 5}
   dest := make([]int, 5)

   count := copy(dest, src)

   fmt.Println("Source size is less than Destination size")
   fmt.Printf("src: %v\n", src)
   fmt.Printf("dest: %v\n", dest)
   fmt.Printf("Number of copied elements: %d\n", count)
}

func srcSizeIsEqualToDestSize() {
   src := []int{1, 2, 3, 4, 5}
   dest := make([]int, 10)

   count := copy(dest, src)

   fmt.Println("Source size is equal to Destination size")
   fmt.Printf("src: %v\n", src)
   fmt.Printf("dest: %v\n", dest)
   fmt.Printf("Number of copied elements: %d\n", count)
}

func srcSizeIsGreaterToDestSize() {
   src := []int{1, 2, 3, 4, 5}
   dest := make([]int, 2)

   count := copy(dest, src)

   fmt.Println("Source size is greater than Destination size")
   fmt.Printf("src: %v\n", src)
   fmt.Printf("dest: %v\n", dest)
   fmt.Printf("Number of copied elements: %d\n", count)
}

We expect to see these results when executing the code:

Source size is equal to Destination size
src: [1 2 3 4 5]
dest: [1 2 3 4 5 0 0 0 0 0]
Number of copied elements: 5
Source size is less than Destination size
src: [1 2 3 4 5]
dest: [1 2 3 4 5]
Number of copied elements: 5
Source size is greater than Destination size
src: [1 2 3 4 5]
dest: [1 2]
Number of copied elements: 2

On the other hand, if you update value of elements in destination slice without affecting the elements in source slice.

func checkCopy() {
	src := []int{1, 2, 3, 4, 5}
	dest := make([]int, 5)

	count := copy(dest, src)

	fmt.Printf("src: %v\n", src)
	fmt.Printf("dest: %v\n", dest)
	fmt.Printf("Number of copied elements: %d\n", count)
	fmt.Println("Update dest elements")
	dest[0] = 100
	dest[1] = 200
	fmt.Printf("src: %v\n", src)
	fmt.Printf("dest: %v\n", dest)
}

We can expect this result to appear:

src: [1 2 3 4 5]
dest: [1 2 3 4 5]
Number of copied elements: 5
Update dest elements
src: [1 2 3 4 5]
dest: [100 200 3 4 5]

The elements in source slice remains unchanged.

That’s how easy it is to copy slices in Go.

Have fun!