片作家与作家的指针

This code results in a nil dereference:

tmpfile, _ := ioutil.TempFile("", "testing")
defer tmpfile.Close()
tmpwriter := bufio.NewWriter(tmpfile)
defer tmpwriter.Flush()
tmpwriter.WriteString("Hello World
")
a := make([]*bufio.Writer, 1)
a = append(a, tmpwriter)
a[0].WriteString("It's Me") //Error here

This code results in no nil dereference, but doesn't actually write anything to the temp file:

tmpfile, _ := ioutil.TempFile("", "testing")
defer tmpfile.Close()
tmpwriter := bufio.NewWriter(tmpfile)
defer tmpwriter.Flush()
tmpwriter.WriteString("Hello World
")
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")

What principle am I missing here? What's the idiomatic way to store a slice of writers, and what's going on under the hood to cause the nil in the first case, and what looks like a pointer dereference causing a side effect on the writer itself in the second?

a := make([]*bufio.Writer, 1)
a = append(a, tmpwriter)

then len(a) == 2 and a[0] == nil, a[1] == tempwriter, so

a[0].WriteString("It's Me")

panic with nil reference.


May be you need:

var a []*bufio.Writer
a = append(a, tmpwriter)
a[0].WriteString("It's Me")

or

a := []*bufio.Writer{tmpwriter}
a[0].WriteString("It's Me")