go / intermediate
Snippet
Creating Custom Sets Using Empty Struct Maps
Since Go doesn't provide a built-in Set collection, developers implement it using a map. By using struct{} as the value type, we consume 0 bytes of storage for the values, making it highly memory-efficient.
snippet.go
go
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
package mainimport "fmt"type Set struct {data map[string]struct{}}func NewSet() *Set {return &Set{data: make(map[string]struct{})}}func (s *Set) Add(item string) {s.data[item] = struct{}{}}func (s *Set) Has(item string) bool {_, exists := s.data[item]return exists}func main() {s := NewSet()s.Add("golang")fmt.Println("Contains golang:", s.Has("golang"))}
Breakdown
1
data map[string]struct{}
Uses map keys for set elements and an empty struct as a zero-byte value.
2
s.data[item] = struct{}{}
Adds an item to the map using struct{}{} to consume no memory for the map value.
3
_, exists := s.data[item]
Checks key membership in the map using a comma-ok idiom.