3.7 Go pointer

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 namestored 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, *intand *stringso 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)
}

Guess you like

Origin www.cnblogs.com/open-yang/p/11256771.html