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

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

PHPz
Release: 2024-02-14 10:00:09
forward
1280 people have browsed it

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

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

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!

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