go - 作家片段与作家指针

标签 go

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

我在这里缺少什么原则?存储 writer 片段的惯用方法是什么?在第一种情况下,幕后发生了什么导致 nil,在第二种情况下,什么看起来像指针取消引用对 writer 本身造成了副作用?

最佳答案

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

然后 len(a) == 2 and a[0] == nil, a[1] == tempwriter, 所以

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

没有引用的 panic 。


您可能需要:

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

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

关于go - 作家片段与作家指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018683/

相关文章:

arrays - 在 MongoDB Golang 中存储 slice 和嵌套结构

time - golang time.Sleep 错误?

go - Zap 堆栈跟踪与谷歌云上的错误消息

Golang io/ioutil NopCloser

go - 如何定义我自己的 helm 模板函数

go - 使用标准库的函数处理程序 GoLang

compiler-errors - go 和 gwan 未使用的变量

go - 如何在 Go 中中止 net.Dial 调用?

http - 如何在http get请求中设置 header ?

去切换失败