Overview
Write one generic Unique function in Go that removes duplicates from slices of any comparable type, keeping the order in which items first appear.
- a type parameter: [T comparable]
- comparable allows == and map keys
- map iteration order is random
Short Course
A generic function takes a type parameter, so
func Unique[T comparable](items []T) []T works for strings, ints and more;
comparable allows == and map keys. Trap: ranging over a map gives a random
order; build the result in input order.
func Count[T comparable](items []T, x T) int {
n := 0
for _, v := range items {
if v == x {
n++
}
}
return n
}
Task
Write Unique[T comparable](items []T) []T: the items without duplicates,
each kept where it first appears. Example:
Unique([]string{"go", "web", "go"}) → [go web].
Test Suites
Pending
Next
Output