append函数输出奇怪的结果。

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

append func gives a weird output

问题

主要原因是切片(slice)在追加时会共享底层数组。在代码中,切片y和切片z都是通过追加切片x来创建的。当使用append函数追加元素时,如果切片的容量不足以容纳新元素,Go语言会创建一个新的底层数组,并将原有的元素复制到新的数组中。但是,如果切片的容量足够,Go语言会直接在原有的底层数组上追加新元素。

在代码中,切片y和切片z的容量都足够容纳新元素,因此它们共享同一个底层数组。当追加元素4时,切片xyz都指向了同一个底层数组,因此它们的输出结果都是[0 1 2 4]

如果你想要得到[0 1 2 3]的输出结果,可以使用copy函数创建一个新的切片,而不是直接追加切片x。以下是修改后的代码:

func main() {
    x := []int{}
    x = append(x, 0)
    x = append(x, 1)
    x = append(x, 2)
    y := make([]int, len(x))
    copy(y, x)
    z := make([]int, len(x))
    copy(z, x)
    y = append(y, 3)
    z = append(z, 4)
    fmt.Println(y, z)
}

这样修改后,切片y和切片z将分别拥有独立的底层数组,输出结果将为[0 1 2 3] [0 1 2 4]

英文:
func main() {
	x := []int{}
	x = append(x, 0)
	x = append(x, 1)
	x = append(x, 2)
	y := append(x, 3)
	z := append(x, 4)
	fmt.Println(y, z)
}

> Why the output is this? [0 1 2 4] [0 1 2 4] Instead of this? [0 1 2 3]
> [0 1 2 4]

答案1

得分: 1

这将实现您期望的输出:[0 1 2 3] [0 1 2 4]

package main

import "fmt"

func main() {
	x := []int{}
	x = append(x, 0)
	x = append(x, 1)
	x = append(x, 2)
	y := []int{}
	z := []int{}
	y = append(y, x...)
	z = append(z, x...)
	y = append(y, 3)
	z = append(z, 4)
	fmt.Println(y, z)
}
英文:

This would achieve your expected output of [0 1 2 3] [0 1 2 4]

package main

import "fmt"

func main() {
	x := []int{}
	x = append(x, 0)
	x = append(x, 1)
	x = append(x, 2)
	y := []int{}
	z := []int{}
	y = append(y, x...)
	z = append(z, x...)
	y = append(y, 3)
	z = append(z, 4)
	fmt.Println(y, z)
}

答案2

得分: 1

如果您使用这个打印语句,您会发现append(x,3)append(x,4)返回的是相同的指针。这就是原因。

fmt.Printf("%p\n", &x)
fmt.Printf("%p\n", append(x, 3))
fmt.Printf("%p\n", append(x, 4))

0xc000010030
0xc00001c0a0
0xc00001c0a0
英文:

If you use this print statement, you can see append(x,3) and append(x,4) are returning the same pointer. That's the reason.

fmt.Printf("%p\n", &x)
fmt.Printf("%p\n", append(x, 3))
fmt.Printf("%p\n", append(x, 4))

0xc000010030
0xc00001c0a0
0xc00001c0a0

huangapple
  • 本文由 发表于 2022年9月25日 20:56:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/73844654.html
匿名

发表评论

匿名网友

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

确定