Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

go - Why does append() modify the provided slice? (See example)

You can run the example code on Go Playground.

Here is the code:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    fmt.Println(numbers)
    _ = append(numbers[0:1], numbers[2:]...)
    fmt.Println(numbers)
}

Output:

[1 2 3 4 5]
[1 3 4 5 5]

Why was the numbers slice modified by append? Is this expected behavior and if yes, could you explain to me why? I thought append doesn't modify its arguments.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...