OneBite.Dev - Coding blog in a bite size

copy an array in Go

Code snippet on how to copy an array in Go

  // Create two slices for the original array and destination
  source := []string{"apple", "orange", "lemon"}
  destination := make([]string, len(source))

  // Use a for loop to iterate through each item in the original array
  for i, v := range source {
    
    // Copy the item to the destination slice
    destination[i] = v
  }

This code demonstrates how to copy an array in Go. First, two slices are created, one to hold the original array (called source) and one to hold the resulting array (called destination). The destination slice length is set to the same size as the source slice.

Next, a for loop is used to iterate through the items in the source array. For each item, it is copied to the corresponding position in the destination array. At the end of the loop, the destination array contains all of the items from the source array.

go