How to implement BitSet with Go?
go
Solution
Declare bitSet as a private struct:
type bitSet struct {
len int
array []uint64
}
Expose the interface BitSet:
type BitSet interface {
Has(pos int) bool
Add(pos int) bool
Len() int
}
Also expose a function NewBitSet:
func NewBitSet(len int) BitSet {
return &bitSet{len, make(uint64, (len+7) / 8) }
}
This is a Go way for encapsulation: share an interface, not the implementation.
Problem
I didn't find a BitSet package in Go, so I tried to implement it. I'd like to use a array of uint64 to store the bits. I need the number of bits to allocate the uint64 array. With Java, I can define a constructor that takes an integer. While Go doesn't provide constructor, how can I properly initialize the BitSet 'object' when user call new()?