Unique function for arrays/slices in Go

How to write a functional Unique function in golang using generics, including a unit test. Quite handy when processing data!

Unique returns a new slice containing the unique elements from the input slice.

func Unique[A comparable](input []A) []A {
	seen := make(map[A]bool)
	var result []A
	for _, v := range input {
		if !seen[v] {
			seen[v] = true
			result = append(result, v)
	return result

and this is a unittest for the function:

func TestUnique(t *testing.T) {
	input := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
	expected := []int{1, 2, 3, 4}
	result := util.Unique(input)
	if !reflect.DeepEqual(expected, result) {
		t.Errorf("Expected %v, got %v", expected, result)

Linked Technologies

What it's made of

illustration of Go

Fast, simple, and efficient. Ideal for solopreneurs, Go's straightforward syntax and powerful performance allow for quick development and deployment.

Linked Categories

Where it's useful

illustration of Data Engineering
Data Engineering

Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.