Golang: Unraveling the Mystery of Array Passing
In this article, we delve into the enigma surrounding passing arrays in Golang. Unlike some other languages where arrays are implicitly passed by reference, Golang's approach is distinctive.
Exploring the Confusion
Alan A.A. Donovan and Brian W. Kernighan in "The Go Programming Language" suggest that arrays in Go are not implicitly passed by reference. However, a close examination of the following code may raise questions:
<code class="go">func main() { tab := []int{1, 2, 3} fmt.Println(tab) // Results in [1 2 3] reverse(tab) fmt.Println(tab) // Results in [3 2 1] } func reverse(tab []int) { for i, j := 0, len(tab)-1; i < j; i, j = i+1, j-1 { tab[i], tab[j] = tab[j], tab[i] } }</code>
Despite not passing the array by reference, the reverse function alters the original array. This behavior seems akin to C .
The Truth Revealed
The key lies in recognizing that the variables tab (in main) and the parameter tab (in reverse) are not arrays but rather slices of an underlying array. Unlike arrays, slices are just headers that describe a portion of an array. When slices are passed around, only these headers are copied, pointing to the same backing array.
Essential Distinctions
In Go, array lengths are inherent to their type (e.g., [3]int), indicating that actual arrays are passed by value. Slices, however, being mere descriptors, are passed by value, but modifications to their elements affect the underlying array because it is the same for all slices.
Additional Insights
For a deeper understanding, refer to the following resources:
Conclusion
Go's approach to passing arrays is distinct from some other languages. Understanding the difference between arrays and slices is crucial to comprehending this behavior. Slices, serving as flexible headers, allow for modifying the underlying array through different slice copies.
The above is the detailed content of Go: Do Arrays Pass by Reference or Value?. For more information, please follow other related articles on the PHP Chinese website!