Go - slice copy example

In this example, we will show you how to use the built-in copy() function to copy a slice in Go with an example.

The Go provides the built-in copy() function copies a slice.

func copy(dst, src []T) int

The function returns the number of elements copied.

Go - slice copy example

In the example, we copy a slice of integers.


package main

import "fmt"

func main() {

    vals := []int{1, 2, 3, 4, 5}

    vals2 := make([]int, len(vals))

    n := copy(vals2, vals)

    fmt.Printf("%d elements copied\n", n)

    fmt.Println("vals:", vals)
    fmt.Println("vals2:", vals2)
}

Output:

5 elements copied
vals: [1 2 3 4 5]
vals2: [1 2 3 4 5]