MacLochlainns Weblog

Michael McLaughlin's Technical Blog

Site Admin

No Set f(x) in GO

without comments

Curious little tidbit as I continue my exploration of the GO programming language. I discovered that it doesn’t have a native set function that would let you create a set from a list. For example, converting a non-unique list of integers into a sorted set of integers is easy in Python:

a = [1, 2, 3, 1, 7, 6, 2, 5, 1, 3, 2]
for x in sorted(list(set(a))): print(x)

That returns:

1
2
3
5
6
7

Unfortunately, there’s no equivalent to Python’s IDLE (Integrated Development and Learning Environment) for GO. The best you have is to use the GO Playground; which gives you a shell where you can write small functions and your main() method to test concepts.

Here’s the equivalent of the two (or if you like three) lines of Python code in the GO Programming language to print the unique integers in an ascending sort:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// You can edit this code!
// Click here and start typing.
package main
 
import (
	"fmt"
	"sort"
)
 
// Convert a slice of non-unique integers into a set.
func set(slice []int) []int {
	// Define a map and slice.
	keys := make(map[int]bool)
	set := make([]int, 0, len(slice))
 
	// Traverse slice, assign new values as map keys, and assign map keys to new slice.
	for _, val := range slice {
		if !keys[val] {
			keys[val] = true
			set = append(set, val)
		}
	}
 
	// Return the set of integers.
	return set
}
 
func main() {
	// Create a slice of non-unique integers.
	a := []int{1, 2, 3, 1, 7, 6, 2, 5, 1, 3, 2}
 
	// Create a map of unique integers, as keys of the Boolean map.
	b := set(a)
 
	// Sort the unordered keys into ordered keys.
	sort.Ints(b)
 
	// Print the sorted unique results from the original non-unique slice.
	for _, i := range b {
		fmt.Println(i)
	}
}

You can past this into the GO Playground and click the run button to get those same sorted and unique values:

1
2
3
5
6
7

As always, I hope this helps a few users of the blog.

Written by maclochlainn

March 22nd, 2025 at 11:03 pm

Leave a Reply