Home > Net >  How to move elements from one slice to another
How to move elements from one slice to another

Time:12-28

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 function of transfer, I intented to transfer elements of slice arr0 to slice arr1 and empty slice arr0

But it is not successful

Here is my output

[1 2 3 4 5]
[]
transferring...
[1 2 3 4 5]
[]

After transferring, I need the result below. [] [1 2 3 4 5] But actually, arr0, and arr1 in the main function remain as it was!

can someone tell me why this is not ok?

I thought in the memory, it should be like this

enter image description here

after running transfer function

enter image description here

CodePudding user response:

These two lines:

arr1 = &tmp
arr0 = &s

change the local variables arr1 and arr0 within the function. Those variables happen to be pointers, but they are just copies of the input pointers provided by main—they are not references to the input pointers.

If you changed the things the arr1 and arr0 pointers point to, rather than the pointers themselves, then you would see a change to the values provided by main:

*arr1 = tmp
*arr0 = s

CodePudding user response:

@jacobsa has given an excellent answer.

Just keep that in mind. You can achieve the same effect but with better performance. Golang offers an excellent opportunity for this.

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) {
    *arr0, *arr1 = *arr1, *arr0
}
  • Related