The problem is that when you remove an item from the original list, all subsequent items are shifted. But the loop range
does not know that you have changed the base slice and increment of the index as usual, although in this case it should not, because then you will skip the element.
remove
2 , , ("abc"
) .
- range
, , i--
, , , -incremented:
urlList := []string{"test", "abc", "def", "ghi"}
remove := []string{"abc", "test"}
loop:
for i := 0; i < len(urlList); i++ {
url := urlList[i]
for _, rem := range remove {
if url == rem {
urlList = append(urlList[:i], urlList[i+1:]...)
i--
continue loop
}
}
}
fmt.Println(urlList)
:
[def ghi]
:
, + break
:
urlList := []string{"test", "abc", "def", "ghi"}
remove := []string{"abc", "test"}
for i := 0; i < len(urlList); i++ {
url := urlList[i]
for _, rem := range remove {
if url == rem {
urlList = append(urlList[:i], urlList[i+1:]...)
i--
break
}
}
}
fmt.Println(urlList)
.
Alternative
, , ( ) , ( - ).