Copy a Slice
Lesson 13 of 21 in Coddy's Slices and Maps in Golang course.
In Go, there are some built-in functions that we can use with slices, and we already used one of them in the last lesson, which is the <strong>append</strong> function. It allows us to add elements to an existing slice. We call these functions helper functions, and you can add this to the difference between arrays and slices in Go; arrays don't have these functions.
In this lesson, we're going to talk about the <strong>copy</strong> function, which allows us to copy a slice, and it works like this:
str := []string{"Python", "Golang", "Java", "TypeScript"}
newStr := make([]string, 4)
copy(newStr, str)
fmt.Println(newStr)This will be the output:
[Python Golang Java TypeScript]Using the <strong>copy</strong> function, we copy the elements from the <strong>str</strong> slice to the <strong>newStr</strong> slice. The syntax is like this: <strong>copy(destination, source)</strong>.
Now, what if the new slice's capacity is less than the source slice? Let's do an example:
str := []string{"Python", "Golang", "Java", "TypeScript"}
newStr := make([]string, 3)
copy(newStr, str)
fmt.Println(newStr)If we run this, we'll get:
[Python Golang Java]Because the new slice's capacity is 3, so there is space for only 3 elements.
Let's do an example in the opposite case:
str := []int{23, 34, 56, 77}
newStr := make([]int, 6)
copy(newStr, str)
fmt.Println(newStr)Here, the new slice's capacity is bigger than the source slice, so the result will copy the elements, and the rest will be the default value, which in the case of an int is 0:
[23 34 56 77 0 0]Challenge
EasyWrite a program that takes two slices and merges them into a new slice, then prints it to the screen.
In the given code, we define two integer slices.
Here you will need to use the slice operator along with the copy function.
Refer to the hints if you need more help.
Try it yourself
package main
import (
"fmt"
)
func main() {
// two Slices Don't Change This!
str := []int{1, 2, 3, 4}
str2 := []int{5, 6, 7, 8}
// Define New Slice
// Copy element
// Copy with Slice operator
// Print the new Slice
fmt.Println()
}All lessons in Slices and Maps in Golang
1Introduction
Introduction3Slices Behind the Scene
Slice is an ArraySlice with MakeCopy a SliceDelete an ElementRecap Challenge #1Recap Challenge #2