Skip to content

Instantly share code, notes, and snippets.

@siburu
Created December 7, 2015 07:31
Show Gist options
  • Save siburu/09d28fb93aec5706502c to your computer and use it in GitHub Desktop.
Save siburu/09d28fb93aec5706502c to your computer and use it in GitHub Desktop.
You must use a downward loop
// http://stackoverflow.com/questions/29005825/how-to-remove-element-of-struct-array-in-loop-in-golang
package main
func correctDeletion() {
var array [10]int
for i, _ := range array {
array[i] = i
}
s := array[:]
for i := len(s) - 1; i >= 0; i-- {
v := s[i]
println("iterated:", v)
if v == 5 {
s = append(s[:i], s[i+1:]...)
}
}
}
func wrongDeletion() {
var array [10]int
for i, _ := range array {
array[i] = i
}
s := array[:]
for i, v := range s {
println("iterated:", v)
if v == 5 {
s = append(s[:i], s[i+1:]...)
}
}
}
func main() {
println("===== Correct! =====")
correctDeletion()
println()
println("===== Wrong! =====")
wrongDeletion()
}
@ciehanski
Copy link

Very useful, thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment