【发布时间】:2018-12-27 09:11:14
【问题描述】:
下面的 golang(go1.10.2) 代码会给出意外的输出
package main
import (
"bytes"
"fmt"
)
func main() {
var b bytes.Buffer
//Commenting the below line will fix the problem
b.WriteString("aas-")
fmt.Printf("Before Calling - \"%s\"\n", b.String())
b = makeMeMad(b)
fmt.Printf("FinalValue - \"%s\"\n", b.String())
}
func makeMeMad(b bytes.Buffer) bytes.Buffer {
b.WriteString("xcxxcx asdasdas dasdsd asdasdasdasd")
fmt.Printf("Write More - \"%s\"\n", b.String())
/*
//This will fix the problem
var newBuffer bytes.Buffer
newBuffer.WriteString(b.String())
return newBuffer
*/
return b
}
输出
Before Calling - "aas-"
Write More - "aas-xcxxcx asdasdas dasdsd asdasdasdasd"
FinalValue - "aas- "
我期待在输出的最后一行出现“aas-xcxxcx asdasdas dasdsd asdasdasdasd”。谁能解释一下。
【问题讨论】:
-
该问题已发布到 Go 的 github 上,您可以在这里观看:github.com/golang/go/issues/26462
-
所以你所经历的答案在这里:github.com/golang/go/issues/26462#issuecomment-406256821。
bytes.Buffer不应该一开始就按原样传递,总是传递一个指向它的指针。
标签: go pass-by-value