Sling Academy
Home/Golang/Copying Slices in Go: Efficient Techniques

Copying Slices in Go: Efficient Techniques

Last updated: November 24, 2024

Slices in Go are dynamically-sized, flexible views into the elements of an array. They are much more versatile than arrays. When working with slices, it's crucial to know how to copy them efficiently, especially in performance-critical applications.

Basic Copying with the copy Function

The simplest way to copy slices in Go is by using the built-in copy function. This function takes two slices as arguments: the destination slice and the source slice. It copies data from the source slice into the destination and returns the number of elements copied.

package main

import "fmt"

func main() {
    src := []int{1, 2, 3, 4, 5}
    dest := make([]int, len(src))
    
    n := copy(dest, src)
    
    fmt.Println("Elements copied:", n)  // Output: Elements copied: 5
    fmt.Println("Destination slice:", dest)  // Output: [1 2 3 4 5]
}

Intermediate: Copying Portions of a Slice

We can also copy a portion of a slice into another by specifying the required index ranges. This technique uses slicing operations before performing the copy.

package main

import "fmt"

func main() {
    src := []int{1, 2, 3, 4, 5}
    // Prepare destination slice with a specific length
    dest := make([]int, 2)
    
    // Copying a part of the source slice
    copy(dest, src[1:3])
    
    fmt.Println("Partially copied destination slice:", dest)  // Output: [2 3]
}

Advanced: Creating Custom Copy Functions

Sometimes, you may need more control over how elements are copied, for example, by applying transformations or dealing with complex data structures. You can achieve this by writing a custom copy function.

package main

import "fmt"

func customCopy(dest, src []int, filterFunc func(int) bool) int {
    var count int
    for _, value := range src {
        if filterFunc(value) {
            dest[count] = value
            count++
            if count == len(dest) {
                break
            }
        }
    }
    return count
}

func main() {
    src := []int{1, 2, 3, 4, 5}
    dest := make([]int, 3)
    
    n := customCopy(dest, src, func(x int) bool {
        return x%2 != 0
    })
    fmt.Println("Elements copied:", n)  // Output: Elements copied: 3
    fmt.Println("Filtered destination slice:", dest)  // Output: [1 3 5]
}

In the above example, the custom copy function copies only odd numbers from the src slice to the dest slice. Such functions offer more flexibility for specific requirements.

Next Article: Passing a Slice to a Function as an Argument in Go

Previous Article: Creating Slices from Arrays in Go

Series: Working with Slices in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant