此代码导致零取消引用:
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
此代码不会导致零解除引用,但实际上不会向临时文件写入任何内容:
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")
我在这里错过了什么原则?什么是存储一部分作者的惯用方法,以及在第一种情况下导致nil的内容是什么,以及在第二种情况下看起来像指针取消引用会对作者本身造成副作用?
答案 0 :(得分:2)
a := make([]*bufio.Writer, 1)
a = append(a, tmpwriter)
然后 len(a)== 2和a [0] == nil,a [1] == tempwriter, 所以
a[0].WriteString("It's Me")
恐慌与零参考。
可能是你需要的:
var a []*bufio.Writer
a = append(a, tmpwriter)
a[0].WriteString("It's Me")
或
a := []*bufio.Writer{tmpwriter}
a[0].WriteString("It's Me")