Skip to content

Instantly share code, notes, and snippets.

@christophberger
Last active October 1, 2019 05:35
Show Gist options
  • Save christophberger/1d6e1a8192a271e14ad7fb9df01528f2 to your computer and use it in GitHub Desktop.
Save christophberger/1d6e1a8192a271e14ad7fb9df01528f2 to your computer and use it in GitHub Desktop.
I don't know the theory;please give me a answer!!thank you
package main
import (
"fmt"
)
func main() {
x := make([]int, 1, 10)
var a []int
fmt.Println(" a x ")
for i := 0; i < 12; i++ {
a = append(x, i)
fmt.Printf("%p---%p---%v----%v---%v === %p---%p---%v----%v---%v\n", a, &(a[0]), len(a), cap(a), a, x, &(x[0]), len(x), cap(x), x)
}
fmt.Println("--------------------------------------------------")
fmt.Printf("%p---%p---%v----%v---%v === %p---%p---%v----%v---%v\n", a, &(a[0]), len(a), cap(a), a, x, &(x[0]), len(x), cap(x), x)
fmt.Println("a:", a)
fmt.Println("x:", x)
}
@christophberger
Copy link
Author

(This gist was creted from AppliedGo/concurrencyslower#3)

Hi JieshuaiCui,

I don't know your question, but there is a central error in your code that produces the unexpected result.

When using append(), you need to assign the return value back to the same slice. So instead of a = append(x, i), try x = append(x, i).

Why does append() work that way? The slice is passed into the function as a value. Therefore, if the function changes that value, then there must be some way to pass the changes back to the caller. append() solves this task by simply returning the changed value.

See the below code for a working example, or run the code directly at the Go playground: https://play.golang.org/p/8X_Eg5jgKQq

package main

import (
	"fmt"
)

func main() {
	x := make([]int, 1, 10)

	var a []int
	for i := 0; i < 12; i++ {

		x = append(x, i)  // <-- assign the result of append() back to the same slice
		fmt.Printf("%p---%p---%v----%v---%v\n", x, &(x[0]), len(x), cap(x), x)
	}

	fmt.Println("--------------------------------------------------")
	fmt.Printf("%p---%p---%v----%v---%v\n", a, x, &(x[0]), len(x), cap(x), x)
	fmt.Println("a:", a)
	fmt.Println("x:", x)
}

The creators of the append() function could also have chosen to have append() request a pointer to an array as input, like so:

var a []int
append(&a, 1) 

Both of these two approaches have their pros and cons. The Go team decided against the pointer solution and for the return value solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment