Go · Level 2 Generics

Generics

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

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
}

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].

solution.go
Test Suites Pending
Output