pu369com

golang 指针在struct里的应用

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

posted on 2020-06-05 11:30  pu369com  阅读(218)  评论(0编辑  收藏  举报

导航