Bloom Filter Probabilistic Membership (Go)
Implement a Go bloom filter with k hash functions for probabilistic membership testing.
Code
package main
import "hash/fnv"
type BloomFilter struct {
bits []byte
size int
k int
}
func newBloom(size, k int) *BloomFilter { return &BloomFilter{bits: make([]byte, size), size: size, k: k} }
func (bf *BloomFilter) hash(item string, seed int) int {
h := fnv.New32a()
h.Write([]byte{byte(seed)})
h.Write([]byte(item))
return int(h.Sum32()) % bf.size
}
func (bf *BloomFilter) Add(item string) { for i := 0; i < bf.k; i++ { bf.bits[bf.hash(item, i+1)] = 1 } }
func (bf *BloomFilter) Contains(item string) bool { for i := 0; i < bf.k; i++ { if bf.bits[bf.hash(item, i+1)] == 0 { return false } }; return true }How it works
Count the functions newBloom, hash, Add and Contains as the entire surface area of Bloom Filter Probabilistic Membership (Go).
What to watch for
- The whole dependency story is the language version itself.
Applying it
Entry signature: func (bf *BloomFilter) Add(item string)
Add hangs off BloomFilter: obtain an instance and invoke the method on it.
Statements that matter
func newBloom(size, k int) *BloomFilter { return &BloomFilter{bits: make([]byte, size), size: size, k: k} }
func (bf *BloomFilter) Add(item string) { for i := 0; i < bf.k; i++ { bf.bits[bf.hash(item, i+1)] = 1 } }
func (bf *BloomFilter) hash(item string, seed int) int {
h := fnv.New32a()
h.Write([]byte{byte(seed)})
h.Write([]byte(item))
return int(h.Sum32()) % bf.size
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `hash/fnv`. The file defines `newBloom`, `hash`, `Add` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.