V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
pmispig
V2EX  ›  程序员

请教一个 go 指针拷贝的问题

  •  
  •   pmispig · 2019-04-12 20:00:17 +08:00 · 1452 次点击
    这是一个创建于 1833 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package main
    
    import "fmt"
    
    type W struct {
        Id   int
        t *T
    }
    
    func createT() *T{
        var t *T = &T{}
        t.Id = 1
        return t
    }
    
    func (w W) setT(){
        t := createT()
        fmt.Println(t.Id)
        w.t = t
    }
    
    type T struct {
        Id   int
        Name string
    }
    
    
    func main() {
        w := W{}
        w.setT()
    
        fmt.Println(w.t.Id)
    }
    

    请问最后为什么会报空指针错误?因为局部变量的指针被回收了吗?请问怎么解决呢

    3 条回复    2019-04-13 00:31:47 +08:00
    n329291362
        1
    n329291362  
       2019-04-12 20:08:11 +08:00   ❤️ 1
    func (w W) setT

    func (w *W) setT
    pmispig
        2
    pmispig  
    OP
       2019-04-12 20:13:12 +08:00
    @n329291362 明白了,谢谢
    Linxing
        3
    Linxing  
       2019-04-13 00:31:47 +08:00 via iPhone
    我也放过一样的错误
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1284 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:34 · PVG 07:34 · LAX 16:34 · JFK 19:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.