First of all, assignment in GO is all value passing
a := 1
b := a
x := Struct{}
y := x
Copy the code
They all have independent space in memory, which is the process of copy, so if you change a property of Y here, it doesn’t affect X
What if we want two variables to point to the same memory? We can use a reference type:
y := &x
Copy the code
In this case, y is a *Struct, so we can change y, and after we change y, x will also change, because y is now a reference type, and it refers to the memory in which the x structure is located
We can do this by:
y.variable = xxx
Copy the code
To call the structure assignment of the reference type directly, but note that this is the syntax sugar of go, it only helps us to simplify the process of obtaining the real memory through the pointer. The full form should look like this:
(*y).variable = xxx
Copy the code
*y is a backreference to a pointer, which can be understood as *y == x.
In go, we cannot directly manipulate the pointer. For example, in c++, we cannot directly calculate the memory address and then obtain other memory addresses
printNewAddr := y + 4; newAddr := y + 4; newAddr := y + 4Copy the code
Because you can’t manipulate addresses directly, go provides syntactic sugar that lets you manipulate the memory address to which the reference refers by default when using reference types.
Note that we can assign directly to a reference type, but the assignment must also be of a reference type
Y = &struct {} a := 1 b := &a b = 2Copy the code
A special reference type
The make() function creates only reference types, such as slice and map. Slice looks like an array, but it is actually a pointer to the memory space of the array
typeSlice struct {point point // len intcap int
}
Copy the code
So we are implementing:
a := []int
b = a
Copy the code
It looks like B and A are pointing to the same array, which they are. All assignment in GO is value passing, while assignment in slice is a copy of the slice object, i.e., A and B are different slice objects, but they point to the same array
The same is true for Map, which I won’t go into.