How to Copy and Clone Arrays in Go

1. Introduction

Copying and cloning arrays in Go is an operation that can be necessary when you need to preserve the original array before manipulating its data. Unlike slices, when you copy an array in Go, you are creating a new, independent array. This blog post will guide you through the process of copying and cloning arrays in Go.

Definition

Copying an array in Go means creating a new array with the same elements as the original one. Cloning can be done using the built-in copy function, array assignments, or by manually copying elements through iteration.

2. Program Steps

1. Create an original array.

2. Copy the array using array assignment.

3. Clone the array using the copy function.

4. Manually clone the array by iterating through it.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Create an original array
	original := [5]int{1, 2, 3, 4, 5}

	// Step 2: Copy the array using array assignment
	copied := original

	// Step 3: Clone the array using the copy function
	cloned := [5]int{} // Create an empty array with the same size
	copy(cloned[:], original[:]) // Use copy function to clone the array

	// Step 4: Manually clone the array by iterating through it
	manuallyCloned := [5]int{}
	for i, v := range original {
		manuallyCloned[i] = v
	}

	// Printing the arrays
	fmt.Println("Original array:", original)
	fmt.Println("Copied array using assignment:", copied)
	fmt.Println("Cloned array using copy function:", cloned)
	fmt.Println("Manually cloned array:", manuallyCloned)
}

Output:

Original array: [1 2 3 4 5]
Copied array using assignment: [1 2 3 4 5]
Cloned array using copy function: [1 2 3 4 5]
Manually cloned array: [1 2 3 4 5]

Explanation:

1. package main - Declares the main package for the program.

2. import "fmt" - Imports the Format package for input/output operations.

3. original array is initialized with 5 integers.

4. copied is an array that is assigned the original array, creating a copy.

5. cloned array is created empty and then populated with the original array's elements using the copy function.

6. manuallyCloned array is filled with elements from the original array using a for loop with range.

7. The fmt.Println statements are used to print each of the arrays, demonstrating that they all contain the same elements.

8. The output confirms that each method successfully copied or cloned the original array, resulting in three arrays that have the same elements as the original.


Comments