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
// You can edit this code!
// Click here and start typing.
package main
 
import (
	"fmt"
	"sort"
)
 
// Convert a slice of non-unique integers into a map.
func set(slice []int) map[int]bool {
	set := make(map[int]bool)
	for _, val := range slice {
		set[val] = true
	}
	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)
 
	// Create slice for unique map keys with a capacity equal to the length of the slice.
	keys := make([]int, 0, len(b))
 
	// Assign unique key indexes as values in the keys slice.
	for i := range b {
		keys = append(keys, i)
	}
 
	// Sort the unordered keys into ordered keys.
	sort.Ints(keys)
 
	// Print the sorted unique results from the original non-unique slice.
	for _, i := range keys {
		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