Created
December 7, 2015 07:31
-
-
Save siburu/09d28fb93aec5706502c to your computer and use it in GitHub Desktop.
You must use a downward loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful, thank you for sharing!