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.
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.
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!