英文:
Slice of Writers vs pointers to Writers
问题
这段代码导致了空指针解引用:
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") // 这里出错了
这段代码没有导致空指针解引用,但实际上没有向临时文件写入任何内容:
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")
我在这里缺少什么原则?存储一组写入器的惯用方式是什么?在底层发生了什么,导致第一种情况中的空指针,以及第二种情况中似乎是指针解引用导致写入器本身产生副作用?
英文:
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\n")
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\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")
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?
答案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")
英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论