Home  >  Article  >  Backend Development  >  Why does slices.Delete() in golang copy the next element?

Why does slices.Delete() in golang copy the next element?

PHPz
PHPzforward
2024-02-14 10:00:091197browse

Why does slices.Delete() in golang copy the next element?

php editor Zimo will discuss a question about the slices.Delete() function in Golang in this article: Why does it copy the next element? Slices in Golang are a powerful data structure, but the slices.Delete() function exhibits some strange behavior when deleting elements. We will analyze this phenomenon and give possible explanations and causes. By delving deeper into this issue, we can better understand the inner workings and design ideas of slicing in Golang. After reading this article, you will be more familiar with Golang's slicing operations, thereby improving programming efficiency and code quality.

Question content

Sample code:

func main() {
    bar := []string{"Monday", "Tuesday", "Wednesday"}
    slices.Delete(bar, 0, 1) // I want to delete 'Monday'
    fmt.Println(bar)         // prints [Tuesday Wednesday Wednesday]
}

I don't understand why I received a "Wednesday". I'm expecting a two element slice.

Solution

slices.delete Returns the modified slice. You should use this as:

bar=slices.Delete(bar, 0, 1)

This is because the delete operation moves the elements in the slice and then returns a shorter slice, but the original slice bar remains unchanged.

The above is the detailed content of Why does slices.Delete() in golang copy the next element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete