Last active
October 1, 2019 05:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(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 ofa = append(x, i)
, tryx = 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
The creators of the
append()
function could also have chosen to haveappend()
request a pointer to an array as input, like so:Both of these two approaches have their pros and cons. The Go team decided against the pointer solution and for the return value solution.