To create a copy of an array in Go or golang, we can simply assign the array to another variable using the =
operator (assignment) and the contents will be copied over to the new array variable.
TL;DR
package main
import "fmt"
func main(){
// array of elements
nums := [5]int{1, 2, 3, 4, 5}
// copy the `nums` array elements to the
// `numsCopy` using the `=` operator (assignment)
numsCopy := nums
// log to the elements of the
// `numsCopy` variable to the console
fmt.Println(numsCopy) // [1 2 3 4 5]
// mutate the contents in the `numsCopy` array
// to check to see if the contents in
// the original array `nums` changes
numsCopy[0] = 11
// log both the `numsCopy` and `nums` array
fmt.Println(numsCopy, nums) // [11 2 3 4 5] [1 2 3 4 5]
}
For example, let's say we have an array of 5 numbers like this,
package main
func main(){
// array of elements
nums := [5]int{1, 2, 3, 4, 5}
}
Now to copy the elements of the nums
array we can define another variable called numsCopy
and then use the =
operator and then simply assign the values of the nums
array to it.
It can be done like this,
package main
func main(){
// array of elements
nums := [5]int{1, 2, 3, 4, 5}
// copy the `nums` array elements to the
// `numsCopy` using the `=` operator (assignment)
numsCopy := nums
}
Now to check if the numsCopy
has the elements like in the nums
variable, we can first print the numsCopy
variable to the console using the Println()
method from the fmt
standard package like this,
package main
import "fmt"
func main(){
// array of elements
nums := [5]int{1, 2, 3, 4, 5}
// copy the `nums` array elements to the
// `numsCopy` using the `=` operator (assignment)
numsCopy := nums
// log to the elements of the
// `numsCopy` variable to the console
fmt.Println(numsCopy) // [1 2 3 4 5]
}
Now let's mutate the contents on the numsCopy
array and see if the contents of the nums
array change. It can be done like this,
package main
import "fmt"
func main(){
// array of elements
nums := [5]int{1, 2, 3, 4, 5}
// copy the `nums` array elements to the
// `numsCopy` using the `=` operator (assignment)
numsCopy := nums
// log to the elements of the
// `numsCopy` variable to the console
fmt.Println(numsCopy) // [1 2 3 4 5]
// mutate the contents in the `numsCopy` array
// to check to see if the contents in
// the original array `nums` changes
numsCopy[0] = 11
// log both the `numsCopy` and `nums` array
fmt.Println(numsCopy, nums) // [11 2 3 4 5] [1 2 3 4 5]
}
As you can see that the numsCopy
array contents are changed but not the nums
array content. This proves to us that the nums
array is successfully copied into the numsCopy
array variable. Yay ๐ฅณ!
See the above code live in The Go Playground.
That's all ๐.
Top comments (0)