This is a creation in Article, where the information may have evolved or changed.
With regard to parameter passing, there is a sentence in the Golang document:
After they is evaluated, the parameters of the call is passed by value to the
function and the called function begins execution.
Function call parameters are passed as values , not pointer passing or reference passing. After testing, when the parameter variable is a pointer or an implicit pointer type, the parameter is passed as a value (copy of the pointer itself)
Slice is one of the most commonly used data structures, with slice as an example to explain the Golang parameter passing mechanism.
The slice data structure is as follows:
Image
Example code:
package mainimport "fmt"func main(){ slice := make([]int, 3, 5) fmt.Println("before:", slice) changeSliceMember(slice) fmt.Println("after:", slice)}func changeSliceMember(slice []int) { if len(slice) > 1 { slice[0] = 9 }}
The result of the function execution is:
befor:[0 0 0]after:[9 0 0]
Explain:
As can be seen from the data structure diagram, slice can be understood as a struct type, containing the first element of the underlying array address, the array Len, the capacity of three fields, slice object in the parameter pass value process, the value of three fields passed, In fact, the slice address in memory in the Changeslicemember function is not the same as the slice memory address in main, except that the field value is the same , and the value of the first field pointer is the first element address of the underlying array. So you can change the element content directly.
Can be compared with the following code to understand:
package mainfunc main() { value := new(int) modifyFunc(value) println("main:", value)}func modifyFunc(value *int) { value = nil println("modifyFunc:", value)}
Execution Result:
modifyFunc: 0x0main: 0xc820049f30
As you can see, even if the value is a pointer, the value of the variable value in main is not changed, because the value in Modifyfunc is the pointer, as is the value in main, but the two objects themselves are two objects, the reader can understand
1757 reads ∙1 likes