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

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.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

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]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.