Detailed pointer
basic introduction
Different from pointers in C/C++, pointers in Go language cannot be offset and operated, and are safe pointers.
The function parameters in the Go language are all value copies. When we want to modify a variable, we can create a pointer variable that points to the address of the variable. Use pointers to transfer data without copying data. Type pointers cannot be offset and arithmetic. Pointer operations in Go language are very simple, you only need to remember two symbols: & (take the address) and * (take the value based on the address).
Pointer address
Each variable has an address at runtime, and this address represents the location of the variable in memory. In the Go language, the & character is placed in front of the variable to "take the address" operation on the variable. The value types in Go language (int, float, bool, string, array, struct) have corresponding pointer types, such as *int, *int64, *string, etc.
For example: var i int, get the address of num: &i.
package main
import "fmt"
func main(){
var i int = 10
// i的地址
fmt.Println("i的地址 =",&i)
}
The layout of basic data types in memory.
Pointer type
The pointer variable stores an address, and the space pointed to by this address stores the value.
package main
import "fmt"
func main(){
//基本数据类型在内存布局
var i int = 10
// i的地址
fmt.Println("i的地址 =",&i)
//ptr是一个指针变量
//ptr的类型是 *int
//ptr本身的值&i
var ptr *int = &i
fmt.Printf("ptr =%v\n",ptr)
}
operation result:
Memory layout diagram:
Pointer value
After using the & operator to take the address of the ordinary variable, the pointer of this variable will be obtained, and then you can use the * operation on the pointer, that is, the pointer value, the code is as follows.
package main
import "fmt"
func main(){
//指针取值
a := 10
//取变量a的地址,将指针保存到b中
ptr := &a
fmt.Printf("type of ptr: %T\n",ptr)
//指针取值(根据指针去内存取值)
c := *ptr
fmt.Printf("type of c:%T\n",c)
fmt.Printf("type of c:%v\n",c)
}
operation result:
Pointer usage details
- Value types have corresponding pointer types, in the form of *data over and over again, for example, the corresponding pointer of int is *int, and so on.
- Value types include: basic data types int series, float series, bool, string, array and structure struct.