Golang: Copy Slice

By Xah Lee. Date: .

Copy Slice

copy(dst, src)
  • Copy elements of slice from src to dst.
  • The number of elements copied is the smaller of lengths of argument, whichever is shorter.
  • It wipes the values in the dst slice starting at index 0.
  • Return the number of items copied.
  • Arguments must be slice of the same type.
  • In the case of byte slice, the src can be a string too.
package main

import "fmt"

func main() {
	var x = []int{0, 1, 2, 3, 4, 5}
	var y = []int{99, 999}
	copy(y, x)
	fmt.Println(y) // [0 1]
}

Example of copying shorter to longer:

package main

import "fmt"

func main() {
	var x = []int{99, 999}
	var y = []int{0, 1, 2, 3, 4, 5}
	copy(y, x)
	fmt.Println(y) // [99 999 2 3 4 5]
}

Golang, array and slice