1. Go pointer
Each variable at run time has an address, the address represents the variable location in memory.
Go language used &
for variable symbol placed in front of the variable "fetch address" operation.
1.指针默认值nil 2.通过&(取地值符)取变量地址 3.通过*(取值符)透过指针访问目标值
format:
age := 18 ptr:=&age //age是变量名,&age是取age的内存地址,地址交给ptr变量接收,ptr类型是*int
First, basic data types, such as name="yugo"
variable name
stored valueyugo
1) The basic data types, 变量
stored is 值
called 值
type
2) &
the symbol acquisition 变量
of 地址
, e.g.&name
3) 指针类型
variable, are stored in another variable 内存地址
, this 地址
point is stored in the space值
4) Get 指针类型
points 值
, using *
, for example *ptr
, using the * ptr to obtain the value pointed to by ptr
package main import ( "fmt" ) func main() { var name string = "yugo" //查看name变量的内存地址,通过&name取地址 fmt.Printf("name的内存地址:%v\n", &name) //指针变量,存的是内存地址 //ptr指针变量指向变量name的内存地址 var ptr *string = &name fmt.Printf("指针变量ptr的内存地址:%v\n", ptr) //获取指针变量的值,用*ptr //*ptr表示读取指针指向变量的值 fmt.Printf("指针变量ptr指向的值是:%v\n", *ptr) }
5) value types (int, float, bool, string, array, struct) has a corresponding pointer type
For example,
*int
and*string
so on
Value 6) pointer type variable exchange
//想要交换ab的值 func exchange(a, b *int) { *a, *b = *b, *a } func main() { a, b := 3, 4 exchange(&a, &b) fmt.Println(a, b) }
7) using the new () function creates a pointer
func main() { s1 := new(string) //new函数返回指针类型*string,用s1指针变量存储 fmt.Printf("s1类型:%T s1指针变量存储的内存地址是:%v\n", s1, s1) //s1类型*string,值是空字符串的内存地址 //s1="哈哈" 错误写法,s1存储的内存地址 *s1 = "马云说我不爱钱" //*s1取内存地址指向的值 fmt.Println(*s1) }