Go study notes - pointer
Thanks for watching, if you make any mistakes, please leave a message!
1. The basis of pointers
The Go language retains the use of pointers like the C language, but Go's pointers are safe pointers and cannot be used for offset and operations.
First of all, let's distinguish between pointer variables and ordinary variables
- Pointer variable: define a space to store the address of the value
- Ordinary variable: define a space to directly store the value itself
Followed by the pointer type and pointer value :
- Pointer type:
*int
,*string
etc., each corresponding data type can be used as a pointer type.
Similar to the C language, the Go language also uses &
and *
to manipulate variables about pointers
&
: Represents the address symbol, which is used to obtain the address of a variable and store it in another variable*
: Represents the accessor, which is used to obtain the value from the variable at the storage address
func mainPointer() {
var a int
a = 100 //此时a是一个普通的变量
fmt.Printf("%d\n", a) //a存储一个值
b = &a //b存放的是a的地址,此时b是一个指针变量
fmt.Printf("%p\n", b) //b存储一个地址
fmt.Printf("%p\n", &a) //&a存储一个地址
fmt.Println(*&a) //*&a存储一个值
//fmt.Printf("%x\n",&a)
//指针变量的定义,用来存储变量的地址
var p *int //定义指针变量
//*int属于指针类型
//定义指针变量就是定义一个空间用来存储地址
p = &a //把变量a的地址赋值给变量p
fmt.Println(p) //此时p存储的是a的地址
*p = 80 //将p对应的地址赋值为80
fmt.Printf("a=%d,p=%v\n", a, p)
fmt.Printf("a=%d,p=%v", a, *p)
}
2. Expansion of pointers
- A null pointer is a pointer variable that does not take an address. The default value is
nil
//空指针
var q *int
fmt.Println(q)
//指针的空值为nil,系统中默认的值
new()
Function to create an address space of the specified type size
var p *int
p = new(int)
*p = 57
fmt.Println(p, *p)
- pointers as function arguments
package main
import "fmt"
func Swap(num1,num2 *int){
*num1,*num2 = *num2,*num1
fmt.Println(*num1,*num2)
}
func main() {
a := 10
b := 20
Swap(&a,&b)
//普通变量在函数中传递是值传递
//指针变量作为函数参数是地址传递
fmt.Println(a,b)
}