Skip to content

Instantly share code, notes, and snippets.

@NguyenTrungTin
Last active February 27, 2020 14:21
Show Gist options
  • Save NguyenTrungTin/70b16090b52c48dca9f54693c1418d46 to your computer and use it in GitHub Desktop.
Save NguyenTrungTin/70b16090b52c48dca9f54693c1418d46 to your computer and use it in GitHub Desktop.
How to get unique and latest item of slice in Go (Golang)
package main
import (
"fmt"
)
func main() {
sl := []string{"zero", "one", "two", "one", "zero", "three", "five", "four", "five"}
duplicateIndex := []int{}
for i, item := range sl {
theRest := sl[i+1:]
for _, obj := range theRest {
if item == obj {
duplicateIndex = append(duplicateIndex, i)
break
}
}
}
count := 0
for _, index := range duplicateIndex {
sl = append(sl[:(index-count)], sl[(index-count)+1:]...)
count++
}
fmt.Println(sl)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment