此代码导致 nil 取消引用:
tmpfile, _ := ioutil.TempFile("", "testing")
defer tmpfile.Close()
tmpwriter := bufio.NewWriter(tmpfile)
defer tmpwriter.Flush()
tmpwriter.WriteString("Hello World\n")
a := make([]*bufio.Writer, 1)
a = append(a, tmpwriter)
a[0].WriteString("It's Me") //Error here
此代码不会产生 nil 解引用,但实际上不会向临时文件写入任何内容:
tmpfile, _ := ioutil.TempFile("", "testing")
defer tmpfile.Close()
tmpwriter := bufio.NewWriter(tmpfile)
defer tmpwriter.Flush()
tmpwriter.WriteString("Hello World\n")
a := make([]bufio.Writer, 1)
a = append(a, *tmpwriter) //Dereferencing seems to cause the first string not to get written
a[0].WriteString("It's Me")
我在这里缺少什么原则?存储 writer 片段的惯用方法是什么?在第一种情况下,幕后发生了什么导致 nil,在第二种情况下,什么看起来像指针取消引用对 writer 本身造成了副作用?
最佳答案
a := make([]*bufio.Writer, 1)
a = append(a, tmpwriter)
然后 len(a) == 2 and a[0] == nil, a[1] == tempwriter, 所以
a[0].WriteString("It's Me")
没有引用的 panic 。
您可能需要:
var a []*bufio.Writer
a = append(a, tmpwriter)
a[0].WriteString("It's Me")
或
a := []*bufio.Writer{tmpwriter}
a[0].WriteString("It's Me")
关于go - 作家片段与作家指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018683/