VOOZH about

URL: https://www.geeksforgeeks.org/go-language/how-to-copy-one-slice-into-another-slice-in-golang/

⇱ How to copy one slice into another slice in Golang? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to copy one slice into another slice in Golang?

Last Updated : 12 Jul, 2025

In Go, a Slice is a variable-length sequence that can hold elements of the same type. You can’t mix different types of elements in a single slice. To copy one slice into another, Go provides a built-in function called copy(). This function allows you to duplicate the elements from one slice (the source) into another slice (the destination).

Example

package main

 import "fmt"

// Basic slice to be used in all examples
var source = []int{10, 20, 30, 40, 50}

func main() { 
fmt.Println("Source Slice:", source)
}

Syntax

func copy(dst, src []Type) int
  • dst: The destination slice where elements will be copied.
  • src: The source slice from which elements will be copied.
  • The function returns the number of elements copied, which will be the minimum of the lengths of the source and destination slices.

Using the copy() Function

Here’s how to copy the source slice into a destination slice using the copy() function:


Output
Source: [10 20 30 40 50]
Destination: [10 20 30 40 50]
Elements copied: 5

Explanation

  1. Creating the Slices: We create a destination slice named destination using make() that can hold the same number of elements as the source slice.
  2. Copying the Elements: We use the copy() function to copy the elements from the source slice to the destination slice. The copy() function returns the number of elements that were copied.
  3. Displaying the Results: Finally, we print both the source and destination slices, along with the count of elements copied.

Manual Copying with a Loop

You can copy slices manually using a loop.

Syntax

for i := 0; i < len(source); i++ { destination[i] = source[i]}

Example:


Output
Source: [10 20 30 40 50]
Destination: [10 20 30 40 50]

Using a Slice Literal

If you want to create a copy of a slice while initializing it, you can use a slice literal with the append() function.

Syntax

destination = append(destination, source...)

Example:


Output
Source: [10 20 30 40 50]
Destination: [10 20 30 40 50]

Note: Ensure that the destination slice is of equal or greater length than the source slice when using copy(); otherwise, the function will only copy up to the length of the destination slice.

Comment
Article Tags:

Explore