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

2019-04-12 20:00:17 +08:00
 pmispig
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)
}

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

1456 次点击
所在节点    程序员
3 条回复
n329291362
2019-04-12 20:08:11 +08:00
func (w W) setT

func (w *W) setT
pmispig
2019-04-12 20:13:12 +08:00
@n329291362 明白了,谢谢
Linxing
2019-04-13 00:31:47 +08:00
我也放过一样的错误

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/554595

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX