Introduction
Recently, I have read many tutorials or blogs that slices, maps, channels, and func in golang are all "reference transfers". However, on the other hand, all types in golang are value transfers, and I always feel a little confused, so I personally did the test and thought.
Here is the code section:
package main import ( "fmt" ) func test(a *int) { ("Value of the incoming variable:", a) ("The address of the incoming variable:", &a) } func main() { va := 666 vad := &va ("The value required to be passed in:", vad) ("Address of the value you need to pass in", &vad) test(vad) }
Here is the execution result
The value that needs to be passed in: 0xc000018658
The address of the value that needs to be passed in 0xc000006058
The value of the passed variable: 0xc000018658
The address of the variable passed in: 0xc000006060
Thinking and explaining
In other words, the values passed and actually received are pointer variables. The values of these two pointer variables vad and a are both address 0xc000018658 of the variable va pointed to by the pointer.
Then look at the address (pointer) of the pointer a (pointer) 0xc000006060. Compared with the address where the pointer vad is stored outside, 0xc000006058, these two values are different, which means that the pointer type is also value-passing, which means that a copy of the pointer value is passed to the function.
Therefore, the variable a inside function test and the variable external vad are not the same thing at all. a is the replica of vad, but the values of these two variables store the address of the va variable, so operation a will modify the variable va.
From this point of view, I personally think that the expression "slice, map, channel, and func are all reference transmissions" is easy to cause misunderstandings, and I suspect that golang's design treats these things in a special way, which is reference transmissions.
In fact, all types of golang are passed in the form of values. However, for these types, the underlying implementation is that after these types of data are successfully created, the data received by the variable is the address corresponding to these types, or the address of the value received by the assigned variable is the address of the value of these types. It should not be what reference type these types are when passing.
This is the end of this article about the misunderstanding of "citation delivery" in golang. For more related golang citation delivery content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!