In Go, function parameters can be passed by value or by pointer. This distinction is particularly evident when handling arrays.
Passing Arrays by Value
When an array is passed by value as a parameter, a copy of the array is actually passed, not the original array itself. This means that any modifications made to the array within the function do not affect the original array. This approach is suitable when you do not want the function to modify the external array, or when the array is small enough that performance issues are negligible.
Example:
gopackage main import "fmt" func modifyArray(arr [3]int) { arr[0] = 10 // This modifies the first element of the copy fmt.Println("Inside modifyArray:", arr) } func main() { arr := [3]int{1, 2, 3} modifyArray(arr) fmt.Println("In main:", arr) // The original array remains unchanged }
The above code shows that the array is modified within the function, but the original array in the main function is not altered.
Passing Arrays via Pointers
If you want the function to modify the original array, you can pass a pointer to the array. This approach is particularly useful when handling large arrays, as it avoids the high cost of copying the entire array.
Example:
gopackage main import "fmt" func modifyArray(arr *[3]int) { arr[0] = 10 // This modifies the first element of the original array fmt.Println("Inside modifyArray:", *arr) } func main() { arr := [3]int{1, 2, 3} modifyArray(&arr) fmt.Println("In main:", arr) // The original array is modified }
This code passes the address of the array, enabling the function to directly modify the original array. This is typically more efficient, especially for large data structures.
In practical applications, choosing between these methods depends on your specific requirements, such as whether you need to modify the original array and performance considerations. For large arrays, it is generally recommended to use pointer passing to improve efficiency.