github twitter email rss
Merging two slices without duplicates in Go
Jan 26, 2017
1 minute read

Recently I needed to merge a couple of string slices with Go, while ensuring no elements are repeated. While C# has Enumerable.Union and other languages have other similar features, Go does not.

Luckily, it isn’t all too hard in Go, just ever so slightly more verbose.

The best way I found to do this way by using a map, in my case a

map[string]bool
. In this case, what we map to is largely irrelevant.

Please note that my solution does not preserve any sort of order, as Go maps do no such thing, for good reasons.

Here’s the code:

func Merge(one []string, two []string) []string{
	encountered := make(map[string]bool)
	result := make([]string, 0, len(one)+len(two))

	for _, i := range one {
		encountered[i] = true
	}

	for _, i := range two {
		encountered[i] = true
	}

	for k, _ := range encountered {
		result = append(result, []byte(k))
	}

	return result
}

We use the fact that assigning to a map more than once doesn’t cause any duplicates to remove duplicates from our two input slices.

The three for loops and several allocations do irk me though, so if anyone can think of a nicer solution, please let me know!


Back to posts