我注意到Golang的append()有一些奇怪的行为。我理解切片容量如何影响新的底层数组是否被分配的基本概念,但为什么在附加发生影响附加结果后是否使用fmt.Println()
?
package main
import "fmt"
func main() {
a := []byte("AAA")
b := append(a, []byte("BBB")...)
fmt.Println(" a: ", string(a), " b: ", string(b))
c := append(a, []byte("CCC")...)
fmt.Println(" a: ", string(a), " b: ", string(b), " c: ", string(c))
fmt.Println(&b) //try commenting this out and in and running the program
}
在此处链接到运行代码:https://play.golang.org/p/jJ-5ZxTBIn
答案 0 :(得分:3)
你是对的:
这是因为The Go Playground版本旧(go1.6.2
),请使用新版本。
正确的输出(使用go version go1.7rc6
)是:
a: AAA b: AAABBB
a: AAA b: AAACCC c: AAACCC
1- Go Playground(go1.6.2
):
package main
import "fmt"
func main() {
a := make([]byte, 100, 1000)
a = []byte("AAA")
b := append(a, []byte("BBB")...)
fmt.Println(" a: ", string(a), " b: ", string(b))
c := append(a, []byte("CCC")...)
fmt.Println(" a: ", string(a), " b: ", string(b), " c: ", string(c))
//fmt.Println(&b) //try commenting this out and in and running the program
}
输出:
a: AAA b: AAABBB
a: AAA b: AAABBB c: AAACCC
2-围棋游乐场(go1.6.2
):
package main
import "fmt"
func main() {
a := make([]byte, 100, 1000)
a = []byte("AAA")
b := append(a, []byte("BBB")...)
fmt.Println(" a: ", string(a), " b: ", string(b))
c := append(a, []byte("CCC")...)
fmt.Println(" a: ", string(a), " b: ", string(b), " c: ", string(c))
fmt.Println(&b) //try commenting this out and in and running the program
}
输出:
a: AAA b: AAABBB
a: AAA b: AAACCC c: AAACCC
&[65 65 65 67 67 67]
使用go version go1.7rc6
:
package main
import "fmt"
func main() {
a := make([]byte, 100, 1000)
a = []byte("AAA")
b := append(a, []byte("BBB")...)
fmt.Println(" a: ", string(a), " b: ", string(b))
c := append(a, []byte("CCC")...)
fmt.Println(" a: ", string(a), " b: ", string(b), " c: ", string(c))
//fmt.Println(&b) //try commenting this out and in and running the program
}
输出:
a: AAA b: AAABBB
a: AAA b: AAACCC c: AAACCC