8. Go Language - pointer type

A pointer Type Description

  • Ordinary type, variable value is stored, also known as value types.

  • Address acquisition variable, with & such as: var a int, obtaining the address of a: a &

  • Pointer type, a variable is stored address, the address value is stored (an address pointer is stored)

  • Get value of the pointer points to the type of use: such as, var p int, using the value of p * p points to obtain

    var int a = 5 5

    var p * int = &a 0xefefefef --> 5

Second, the use of pointers

1. The actual usage

package main
import (
    "fmt"
)
func main() {
    var cat int = 1
    var str string = "banana"
    // 使用 fmt.Printf 的动词%p输出 cat 和 str 变量取地址后的指针值
    fmt.Printf("%p %p", &cat, &str)
}
运行结果:
0xc042052088 0xc0420461b0

2. Get the value of the pointer from the pointer

In ordinary use variables &obtained after the variable pointer address fetch operator can use the pointer *operation, i.e. the pointer value

package main

import (
    "fmt"
)

func main() {

    // 准备一个字符串类型
    var house = "Malibu Point 10880, 90265"

    // 对字符串取地址, ptr类型为*string
    ptr := &house

    // 打印ptr的类型
    fmt.Printf("ptr type: %T\n", ptr)

    // 打印ptr的指针地址
    fmt.Printf("address: %p\n", ptr)

    // 对指针进行取值操作
    value := *ptr

    // 取值后的类型
    fmt.Printf("value type: %T\n", value)

    // 指针取值后就是指向变量的值
    fmt.Printf("value: %s\n", value)

}

运行结果:
ptr type: *string
address: 0xc0420401b0
value type: string
value: Malibu Point 10880, 90265

取地址操作符&和取值操作符*是一对互补操作符,&取出地址,*根据地址取出地址指向的值。
变量、指针地址、指针变量、取地址、取值的相互关系和特性如下:
对变量进行取地址(&)操作,可以获得这个变量的指针变量。
指针变量的值是指针地址。
对指针变量进行取值(*)操作,可以获得指针变量指向的原变量的值。

3. The pointer modification value

package main
import "fmt"
// 交换函数
func swap(a, b *int) {
    // 取a指针的值, 赋给临时变量t
    t := *a
    // 取b指针的值, 赋给a指针指向的变量
    *a = *b
    // 将a指针的值赋给b指针指向的变量
    *b = t
}
func main() {
// 准备两个变量, 赋值1和2
    x, y := 1, 2
    // 交换变量值
    swap(&x, &y)
    // 输出变量值
    fmt.Println(x, y)
}

运行结果:
2 1

代码说明如下:
第 6 行,定义一个交换函数,参数为 a、b,类型都为 *int,都是指针类型。
第 9 行,将 a 指针取值,把值(int类型)赋给 t 变量,t 此时也是 int 类型。
第 12 行,取 b 指针值,赋给 a 变量指向的变量。注意,此时*a的意思不是取 a 指针的值,而是“a指向的变量”。
第 15 行,将 t 的值赋给 b 指向的变量。
第 21 行,准备 x、y 两个变量,赋值 1 和 2,类型为 int。
第 24 行,取出 x 和 y 的地址作为参数传给 swap() 函数进行调用。
第 27 行,交换完毕时,输出 x 和 y 的值。

*操作符作为右值时,意义是取指针的值;作为左值时,也就是放在赋值操作符的左边时,表示 a 指向的变量。其实归纳起来,*操作符的根本意义就是操作指针指向的变量。当操作在右值时,就是取指向变量的值;当操作在左值时,就是将值设置给指向的变量。

If the switch operating in swap () function is a pointer value

package main
import "fmt"
func swap(a, b *int) {
    b, a = a, b
}
func main() {
    x, y := 1, 2
    swap(&x, &y)
    fmt.Println(x, y)
}

运行结果:
1 2
结果表明,交换是不成功的。上面代码中的 swap() 函数交换的是 a 和 b 的地址,在交换完毕后,a 和 b 的变量值确实被交换。但和 a、b 关联的两个变量并没有实际关联。这就像写有两座房子的卡片放在桌上一字摊开,交换两座房子的卡片后并不会对两座房子有任何影响。

Third, create another method pointer

1. 语法格式
    new(类型)

2. 实例
    str := new(string)
    *str = "ninja"
    fmt.Println(*str)

3. 注解
    new() 函数可以创建一个对应类型的指针,创建过程会分配内存。被创建的指针指向的值为默认值

Guess you like

Origin www.cnblogs.com/hq82/p/11073575.html