Slice of Writers vs pointers to Writers(切片与指向 Writers 的指针)

huangapple go评论75阅读模式
英文:

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")

huangapple
  • 本文由 发表于 2013年9月26日 11:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/19018683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定