8
2 ways to delete an element from a slice
source link: https://yourbasic.org/golang/delete-element-slice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2 ways to delete an element from a slice
yourbasic.org/golang
Fast version (changes order)
a := []string{"A", "B", "C", "D", "E"}
i := 2
// Remove the element at index i from a.
a[i] = a[len(a)-1] // Copy last element to index i.
a[len(a)-1] = "" // Erase last element (write zero value).
a = a[:len(a)-1] // Truncate slice.
fmt.Println(a) // [A B E D]
The code copies a single element and runs in constant time.
Slow version (maintains order)
a := []string{"A", "B", "C", "D", "E"}
i := 2
// Remove the element at index i from a.
copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index.
a[len(a)-1] = "" // Erase last element (write zero value).
a = a[:len(a)-1] // Truncate slice.
fmt.Println(a) // [A B D E]
The code copies len(a) - i - 1 elements and runs in linear time.
Further reading
Slices and arrays in 6 easy steps
Share:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK