Open In App
Related Articles

Copy an Array by Value and Reference into Another Array in Golang

Improve Article
Save Article
Like Article

Array in Golang is a numbered sequence of elements of the same type. The size of the array is fixed. We can access the elements by their index. You can declare an array of size n and type T specifying this way mentioned below.

var array[n]T 

Go doesn’t have an inbuilt function to copy an array to another array. There are two ways of copying an array to another array:

  • By Value
  • By Reference

1. Copying By Value: If we copy an array by value and later changes are made in values of original array, the same changes won’t be reflected in the copy of the original array.

2. Copying By Reference: If we copy an array by reference and later make any changes in the original array, then they will reflect in the copy of the original array created.


// Golang program to copy an array by value
// and reference into another array
package main
import "fmt"
func main() {
    // original string
    strArray := [3]string{"Apple", "Mango", "Guava"}
    // data is passed by value
    Arraybyval := strArray
    // data is passed by reference
    Arraybyref := &strArray
    fmt.Printf("strArray: %v\n", strArray)
    fmt.Printf("Arraybyval : %v\n", Arraybyval)
    fmt.Printf("*Arraybyref : %v\n", *Arraybyref)
    strArray[0] = "Watermelon"
    fmt.Printf("After making changes")
    fmt.Printf("strArray: %v\n", strArray)
    fmt.Printf("Arraybyval: %v\n", Arraybyval)
    fmt.Printf("*Arraybyref: %v\n", *Arraybyref)


strArray: [Apple Mango Guava]
Arraybyval : [Apple Mango Guava]
*Arraybyref : [Apple Mango Guava]
After making changesstrArray: [Watermelon Mango Guava]
Arraybyval: [Apple Mango Guava]
*Arraybyref: [Watermelon Mango Guava]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 08 Jun, 2020
Like Article
Save Article
Similar Reads
Related Tutorials