Go copy() Function

beginner
22 min

Go copy() Function

Welcome to a comprehensive guide on the copy() function in Go (Golang)! In this lesson, we'll delve deep into understanding this powerful tool and its practical applications. By the end of this tutorial, you'll be well-equipped to manipulate and duplicate data with confidence. 🎯

What is the copy() function?

The copy() function is a built-in function in Go that creates a duplicate of a slice (array-like structure). It's incredibly useful when you need to make a copy of a slice without affecting the original. 💡

Why use the copy() function?

Imagine you have a slice of values, and you want to modify a portion of it without altering the entire slice. In such cases, using the copy() function to create a copy allows you to manipulate the copy freely while keeping the original intact. ✅

The copy() function syntax

The copy() function takes two arguments: the source slice and the destination slice, where the copied data will be stored.

go
func copy(dst, src []Type) int

Here, Type represents the type of elements in the slices (e.g., int, string, etc.).

Practical example 1: Copying an int slice

Let's create two slices of integers and copy one slice to another using the copy() function.

go
package main import "fmt" func main() { originalSlice := []int{1, 2, 3, 4, 5} copySlice := make([]int, len(originalSlice)) n := copy(copySlice, originalSlice) fmt.Println("Copied:", copySlice) fmt.Println("Number of elements copied:", n) }

When you run this program, you'll see the following output:

Copied: [1 2 3 4 5] Number of elements copied: 5

Practical example 2: Copying a string slice

Now let's copy a slice of strings and verify that the original slice remains unchanged.

go
package main import "fmt" func main() { originalSlice := []string{"apple", "banana", "cherry"} copySlice := make([]string, len(originalSlice)) n := copy(copySlice, originalSlice) fmt.Println("Copied:", copySlice) fmt.Println("Number of elements copied:", n) fmt.Println("Original slice:", originalSlice) }

The output will be:

Copied: [apple banana cherry] Number of elements copied: 3 Original slice: [apple banana cherry]

Notice how the original slice remains unchanged, but the copied slice has been successfully created using the copy() function.

Quiz

Quick Quiz
Question 1 of 1

What is the primary purpose of the `copy()` function in Go?

By now, you should have a solid understanding of the copy() function in Go. Remember, the copy() function is a valuable tool for duplicating slices while preserving the original data. Happy coding, and stay tuned for more exciting Golang tutorials! 💡📝