Bloom Filter Probabilistic Membership (Go)

Implement a Go bloom filter with k hash functions for probabilistic membership testing.

GoData Integrity

Code

gosnippet
21 lines
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

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.