Skip to content

Storing large sets of integers in Go with the bitset package

A bitset stores a set of non-negative integers as an array of bits: bit i is 1 if i is in the set. A set of integers below one million fits in about 125 KB (one million bits), far less than a map[uint]bool holding the same values, which pays for keys, values and hash buckets. Set operations such as union and intersection run a word (64 bits) at a time.

The trade-off: memory is proportional to the largest value in the set, not the number of values. If you store just the number 1,000,000,000, you pay for a billion bits. For sparse sets of large numbers, use a map or a compressed bitmap such as Roaring.

Terminal window
go get github.com/bits-and-blooms/bitset
package main
import (
"fmt"
"github.com/bits-and-blooms/bitset"
)
func main() {
// New takes an initial length in bits. Set grows the bitset if you go past it.
b := bitset.New(100)
// Set and Clear return the bitset, so calls can be chained.
b.Set(1).Set(3).Set(42)
b.Clear(42)
fmt.Println(b.Test(3)) // true
fmt.Println(b.Test(42)) // false
fmt.Println(b.Count()) // 2
// Union and Intersection return a new bitset and leave both inputs unchanged.
a := bitset.New(100)
a.Set(1).Set(2).Set(3)
fmt.Println(a.Intersection(b)) // {1,3}
fmt.Println(a.Union(b)) // {1,2,3}
// Iterate over the set bits with NextSet.
for i, ok := a.NextSet(0); ok; i, ok = a.NextSet(i + 1) {
fmt.Println("bit", i, "is set")
}
}

All indexes are uint, so untyped constants work as shown, but an int variable needs a conversion: b.Set(uint(n)).

OperationReturns a new bitsetModifies the receiver
ANDIntersectionInPlaceIntersection
ORUnionInPlaceUnion
AND NOTDifferenceInPlaceDifference
XORSymmetricDifferenceInPlaceSymmetricDifference

Use the in-place versions in hot loops to avoid allocating a new bitset each time. There are also IntersectionCardinality, UnionCardinality and friends, which return just the count without building the result.

Recent versions add EachSet, which returns an iter.Seq[uint], so you can use a plain range loop:

for i := range a.EachSet() {
fmt.Println("bit", i, "is set")
}

© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)