php editor Apple will introduce you how to move elements from one slice to another. In programming, a slice is a commonly used data structure that can store multiple elements. Sometimes, we need to take an element out of one slice and move it to another slice. This process may involve element deletion, insertion, indexing operations, etc. Next, we will discuss in detail how to implement this operation to help everyone better understand and apply the relevant knowledge of slicing.
package main import ( "fmt" ) func main() { arr0 := []int{ 1,2,3,4,5, } arr1 := []int{} fmt.println(arr0) fmt.println(arr1) fmt.println("transferring...") transfer(&arr0, &arr1) fmt.println(arr0) fmt.println(arr1) } func transfer(arr0 *[]int, arr1 *[]int) { tmp := make([]int, 0) for i:=0;i<len(*arr0);i++ { tmp = append(tmp, (*arr0)[i]) } arr1 = &tmp s := make([]int, 0) arr0 = &s }
For the transfer function, I plan to transfer the elements of slice arr0 to slice arr1 and empty slice arr0
But no success
This is my output
[1 2 3 4 5] [] transferring... [1 2 3 4 5] []
After transfer, I need the following results. [] [1 2 3 4 5] But in fact, arr0 and arr1 in the main function remain the same!
Can someone tell me why this doesn't work?
I think in my memory, it should be like this
After running the transfer function
These two lines:
arr1 = &tmp arr0 = &s
Change local variables arr1
and arr0
within the function. These variables happen to be pointers, but they are just copies of the input pointer provided by main
- they are not references to the input pointer.
If you change what the arr1
and arr0
pointers point to, rather than the pointers themselves, then you will see the value provided by main
change:
*arr1 = tmp *arr0 = s
The above is the detailed content of How to move elements from one slice to another. For more information, please follow other related articles on the PHP Chinese website!