golang 指针在struct里的应用

cmsmdn 2020-06-05

package main

import "fmt"

type OBJ struct {
    A string
    B *int
}

func main() {
    var data int = 0
    addr := &data
    obj1 := OBJ{
        A: "aaa",
        B: addr,
    }
    obj2 := OBJ{
        A: "bbb",
        B: addr, //与obj1的B指向了同一地址
    }
    *(obj1.B) = 1 //用obj1修改data的值
    fmt.Printf("value is %+v\n", obj1)
    fmt.Printf("value is %+v\n", obj2)
    fmt.Println(*(obj2.B)) //从obj2的B获取的值也变量了1
}

参考:https://www.cnblogs.com/si812cn/p/9625972.html

相关推荐