Home »
Golang
Go Pass an Array to Function
Last Updated : July 21, 2025
In Go, arrays are passed to functions by value, which means a copy of the entire array is passed. Any modification made inside the function does not affect the original array unless pointers are used explicitly.
Passing an Array to a Function
You can pass an array to a function by specifying its type and length in the function parameters. However, remember that it creates a copy of the array, not a reference.
Example
The following example illustrates that arrays in Go are passed by value, so modifications made to the array inside a function do not affect the original array in the calling function:
package main
import "fmt"
func modifyArray(arr [3]int) {
arr[0] = 100
fmt.Println("Inside function:", arr)
}
func main() {
nums := [3]int{1, 2, 3}
modifyArray(nums)
fmt.Println("In main:", nums)
}
When you run the above code, the output will be:
Inside function: [100 2 3]
In main: [1 2 3]
Explanation
- The array
nums
is passed to the modifyArray
function as a copy.
- Changes inside the function do not reflect in the original array because they affect the copied version.
Passing Array by Reference
If you want the function to modify the original array, pass a pointer to the array.
Example
The following example shows how to pass an array to a function by reference in Go using a pointer, allowing the function to modify the original array:
package main
import "fmt"
func modifyArrayByRef(arr *[3]int) {
arr[0] = 200
fmt.Println("Inside function:", *arr)
}
func main() {
nums := [3]int{1, 2, 3}
modifyArrayByRef(&nums)
fmt.Println("In main:", nums)
}
When you run the above code, the output will be:
Inside function: [200 2 3]
In main: [200 2 3]
Difference Between Array and Slice Parameters
Arrays are value types, while slices are reference types. Therefore, changes made to arrays in functions do not persist unless passed by reference, unlike slices which can be modified directly.
Key Points
- Arrays are passed by value – a copy is made.
- Modifications inside the function don’t affect the original array unless a pointer is used.
- To modify the original array, pass it by reference using a pointer.
- Array size is part of its type in Go.
Go Pass an Array to Function Exercise
Select the correct option to complete each statement about passing arrays to functions in Go.
- When you pass an array to a function in Go:
- To modify the original array inside a function, you should:
- Which of the following is true?
Advertisement
Advertisement