1

此代码导致 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")

我在这里缺少什么原则?存储一片作者的惯用方式是什么,在第一种情况下导致 nil 的幕后情况是什么,以及在第二种情况下看起来像指针取消引用会导致对作者本身的副作用?

4

1 回答 1

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")
于 2013-09-26T03:25:05.113 回答