Go language pointers
Pointers are easy to learn in the go language, and using pointers in the go language makes it easier to perform some tasks. We all know that a variable is a handy placeholder for referencing a computer's memory address. The address of the go language is &, which is used before a variable to return the memory address of the corresponding variable, the following example shows the variable in memory address:
package"fmt"func main() { varint10 fmt.Printf("变量的地址:%x\n", &a)}
The result of the above instance execution is:
变量的地址: 20818a220
What is a pointer
A pointer variable points to the memory address of a value, similar to a variable and constant, and requires a pointer to be declared before the pointer is used. The pointer declaration format is as follows:
var var_name *var-type
Var-type is a pointer type, var_name is a pointer variable, * is used to specify that the variable is a pointer, and the following is a valid pointer declaration:
var ip *int /* 指向整形 */var fp *float32 /* 指向浮点型 */
How to use pointers
- Define pointer variables;
- Assigning values to pointer variables;
- Access to the value of the address in the pointer variable;
Precede the pointer type with an * sign (prefix) to get the content pointed to by the pointer.
package mainimport"fmt"func main() { varint20 /* 声明实际变量 */ var ip *int /* 声明指针变量 */ ip = &a /* 指针变量的存储地址 */ fmt.Printf("a 变量的地址是: %x\n", &a ) /* 指针变量的存储地址 */ fmt.Printf("ip 变量储存的指针地址: %x\n", ip ) /* 使用指针访问值 */ fmt.Printf("*ip 变量的值: %d\n", *ip )}
The result of the above example output is:
20
Go null pointer
When a pointer is defined and not assigned to any variable, its value is nil. The nil pointer is also called a null pointer, and nil is conceptually null, None, nil, and Null in other languages, all referring to 0 or null values. A pointer variable is usually abbreviated as PTR, as shown in the following example code:
package mainfunc main() { var ptr *int fmt.Printf("ptr 的值为 : %x\n", ptr )}
The result of the above example output is:
0
Null pointer judgment:
ifnil) /* ptr 不是空指针 */ifnil) /* ptr 是空指针 */
Go pointers more content
Next we will introduce more pointer applications in the GO language:
content |
Description |
Go pointer array |
You can define an array of pointers to store addresses |
Pointer to go pointing pointer |
Go supports pointers pointing to pointers |
Go to function pass pointer parameter |
You can change the value of a function call by reference or by an address parameter |
Go language "Tenth article": GO Data structure: pointer