How to move elements from one slice to another

WBOY
Release: 2024-02-10 17:40:08
forward
1049 people have browsed it

How to move elements from one slice to another

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.

Question content

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
}
Copy after login

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]
[]
Copy after login

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

Solution

These two lines:

arr1 = &tmp
arr0 = &s
Copy after login

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!