Article From:https://segmentfault.com/q/1010000012138258
Question:
package main

func Sample(args []string) {
    args = append(args, "D", "E")
}

func main() {
    args := []string{}
    args = append(args, "A","B","C")
        Sample(args)
    for _, arg := range args {    
        println(arg)
    }
}

For example, in the above program (https://play.golang.org/p/0Ch…), I hope that after the execution of the Sample function, the result in args is ABCDE, but the real result is ABC.

That’s not the same as my understanding of slice.

I tried it. In the Sample function, you can modify the string in it.

package main

func Sample(args []string) {
    args[2] = "F"
}

func main() {
    args := []string{}
    args = append(args, "A","B","C")
    Sample(args)
    for _, arg := range args {    
        println(arg)
    }
}

The above procedure (https://play.golang.org/p/Y81…) changed the last element of args to F.

Or because string is also a longer structure, so when the function passes the reference, the args length is fixed. What is the principle?

Answer 0:
func Sample(args []string) {
    println(len(args))
    println(cap(args))
    println(args)
    args = append(args, "D", "E")
    println(len(args))
    println(cap(args))
    println(args)
}

There will be expansion, the address of args has been changed, and the internal array has changed.
But in go there is only value passing, so the args outside is still referred to the previous array.
Args can be returned to the solution.

Answer 1:
package main

func Sample(args *[]string) {
    *args = append(*args, "D", "E")
}

func main() {
    args := []string{}
    args = append(args, "A", "B", "C")
    Sample(&args)
    for _, arg := range args {
        println(arg)
    }
}

The easiest way is to do that.
Another way is to return the array in the Sample method.
In fact, it’s the problem of value passing and pointer passing. You can search some relevant information and see it.

Answer 2:

First of all, golang has only the value transfer, and the slice passes the copy of reflect.SliceHeader, where the Data field points to the underlying array, and the append dilatancy causes the underlying array to redistribute, that is, the direction of the Data has changed.args[2] = "F"It only modifies the value of the underlying array, and the direction of Data remains unchanged.

You can take a look at golang’s official slice introduction of Go Slices: usage and internals..

Leave a Reply

Your email address will not be published. Required fields are marked *