This is a creation in Article, where the information may have evolved or changed.
Todo:golang Pointers Use Precautions
Let's take a look at the simple Example 1:
Output:
1
1
Example 2:
Output:
1
3
Example 1 is the use of value passing, the Add method does not make any changes; Example 2 is the use of pointers, which change the address, thereby changing the address.
In See Example 3:
Output:
MAP[A:AA B:BB]
Map[b:world A:hello]
Found what, TestMap Front no add *, no pointer, how can also change the value? Because map provides key-value functionality, it is used like a pointer-referenced type. Similar to the type of this feature, arrays are sliced, channel,interface. Go Language Pack This kind of pointer reference type, interested can go to read the source code, the variable is preceded by a "*" number, if not to see if it is a map type.
A copy of a value that does not affect the value of the copy, and the pointer changes all variable names at the same address. Example 4:
Output:
Tempbytes: [97 98 99 100 101 102 103 104]
Buf:abcdefgh
Temp3: [98] ABC
Buf:defgh
Buf1:defgh
TEMP1: [+] D
Buf:efgh
Buf1:efgh
Tempbytes: [97 98 99 100 101 102 103 104]
Tempbytes is a variable so the value does not change, buf is the pointer, BUF1 is the alias of buf, the BUF or BUF1 is changed by the operation of the value BUF and BUF1. If you copy a BUF value, you have to recreate the same value pointer, example 5:
Output the results we want:
Tempbytes: [97 98 99 100 101 102 103 104]
Buf:abcdefgh
Temp3: [98] ABC
Buf:defgh
Buf1:abcdefgh
TEMP1: [A]
Buf:defgh
Buf1:bcdefgh
Tempbytes: [97 98 99 100 101 102 103 104]
Go comes with garbage collection, so we don't need to manually handle pointer memory management, so we can focus more on the development of code and improve efficiency.
Wxgzh:ludong86