Home > Software engineering >  append func gives a weird output
append func gives a weird output

Time:09-27

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]

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • go
  • Related