The bitset.BitSet type maps non-negative integers to boolean values. It provides methods for setting, clearing, flipping, and testing bits. Many methods like Set, Clear, and Flip return a *BitSet to allow for method chaining.
Common operations include:
Set(i uint): Sets the bit at index i.Clear(i uint): Clears the bit at index i.Test(i uint) bool: Returns true if the bit at index i is set.NextSet(i uint) (uint, bool): Returns the next set bit index after i and a boolean indicating if one was found.Count() uint: Returns the number of positive bits.Intersection(other *BitSet) *BitSet: Returns the intersection of two bitsets.
If you are using Go 1.23 or better, you can iterate over set bits using EachSet():
for i := range b.EachSet() {}
package main
import (
"fmt"
"math/rand"
"github.com/bits-and-blooms/bitset"
)
func main() {
fmt.Printf("Hello from BitSet!\n")
var b bitset.BitSet
// play some Go Fish
for i := 0; i < 100; i++ {
card1 := uint(rand.Intn(52))
card2 := uint(rand.Intn(52))
b.Set(card1)
if b.Test(card2) {
fmt.Println("Go Fish!")
}
b.Clear(card1)
}
// Chaining
b.Set(10).Set(11)
for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) {
fmt.Println("The following bit is set:", i)
}
if b.Intersection(bitset.New(100).Set(10)).Count() == 1 {
fmt.Println("Intersection works.")
} else {
fmt.Println("Intersection doesn't work???")
}
}