0
0
GoHow-ToBeginner · 3 min read

How to Copy Slice in Go: Simple Syntax and Examples

In Go, you can copy a slice using the built-in copy function, which copies elements from a source slice to a destination slice. You need to create a destination slice with enough length before copying to avoid overwriting or errors.
📐

Syntax

The copy function in Go copies elements from a source slice to a destination slice. Its syntax is:

copy(destinationSlice, sourceSlice)

Here, destinationSlice is the slice where elements will be copied to, and sourceSlice is the slice from which elements are copied. The function returns the number of elements copied, which is the minimum length of the two slices.

go
n := copy(dest, src)
💻

Example

This example shows how to copy a slice of integers from one slice to another. It creates a destination slice with the same length as the source slice and uses copy to duplicate the elements.

go
package main

import "fmt"

func main() {
    src := []int{1, 2, 3, 4, 5}
    dest := make([]int, len(src))
    n := copy(dest, src)
    fmt.Println("Copied elements count:", n)
    fmt.Println("Source slice:", src)
    fmt.Println("Destination slice:", dest)
}
Output
Copied elements count: 5 Source slice: [1 2 3 4 5] Destination slice: [1 2 3 4 5]
⚠️

Common Pitfalls

A common mistake is to copy into a nil or zero-length slice, which results in no elements copied. Also, if the destination slice is smaller than the source, only part of the source is copied. Always create the destination slice with enough length to hold the copied elements.

go
package main

import "fmt"

func main() {
    src := []int{10, 20, 30}
    var dest []int // nil slice
    n := copy(dest, src)
    fmt.Println("Copied elements count with nil dest:", n)

    dest = make([]int, 2) // smaller length
    n = copy(dest, src)
    fmt.Println("Copied elements count with smaller dest:", n)
    fmt.Println("Destination slice after partial copy:", dest)
}
Output
Copied elements count with nil dest: 0 Copied elements count with smaller dest: 2 Destination slice after partial copy: [10 20]
📊

Quick Reference

ConceptDescription
copy(dest, src)Copies elements from src to dest, returns number copied
make([]T, len(src))Create destination slice with length equal to source
Partial copyIf dest shorter, only part of src is copied
Nil or zero-length destNo elements copied, copy returns 0

Key Takeaways

Use the built-in copy function to copy slices in Go.
Always create the destination slice with enough length before copying.
copy returns the number of elements actually copied.
If destination slice is smaller, only part of the source is copied.
Copying into a nil or zero-length slice copies nothing.