如何用Go实现BitSet?

我没有在Go中找到BitSet包,所以我尝试实现它。我想使用uint64数组存储位。

我需要分配uint64数组的位数。使用Java,我可以定义一个接受整数的构造函数。虽然Go不提供构造函数,但是当用户调用new()时如何正确初始化BitSet'对象'呢?


潇潇雨雨
浏览 322回答 3
3回答

阿波罗的战车

如果使用[] uint64切片存储数据,则零切片可以用作空的BitSet。实际上,附加到nil切片会为您分配一个新数组,尽管Language Specification似乎并不能保证这一点。通过这种设置,new(BitSet)将立即可用。例子:bitset.go:package bitsetconst size = 64type bits uint64// BitSet is a set of bits that can be set, cleared and queried.type BitSet []bits// Set ensures that the given bit is set in the BitSet.func (s *BitSet) Set(i uint) {&nbsp; &nbsp; if len(*s) < int(i/size+1) {&nbsp; &nbsp; &nbsp; &nbsp; r := make([]bits, i/size+1)&nbsp; &nbsp; &nbsp; &nbsp; copy(r, *s)&nbsp; &nbsp; &nbsp; &nbsp; *s = r&nbsp; &nbsp; }&nbsp; &nbsp; (*s)[i/size] |= 1 << (i % size)}// Clear ensures that the given bit is cleared (not set) in the BitSet.func (s *BitSet) Clear(i uint) {&nbsp; &nbsp; if len(*s) >= int(i/size+1) {&nbsp; &nbsp; &nbsp; &nbsp; (*s)[i/size] &^= 1 << (i % size)&nbsp; &nbsp; }}// IsSet returns true if the given bit is set, false if it is cleared.func (s *BitSet) IsSet(i uint) bool {&nbsp; &nbsp; return (*s)[i/size]&(1<<(i%size)) != 0}bitset_test.go:package bitsetimport "fmt"func ExampleBitSet() {&nbsp; &nbsp; s := new(BitSet)&nbsp; &nbsp; s.Set(13)&nbsp; &nbsp; s.Set(45)&nbsp; &nbsp; s.Clear(13)&nbsp; &nbsp; fmt.Printf("s.IsSet(13) = %t; s.IsSet(45) = %t; s.IsSet(30) = %t\n",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.IsSet(13), s.IsSet(45), s.IsSet(30))&nbsp; &nbsp; // Output: s.IsSet(13) = false; s.IsSet(45) = true; s.IsSet(30) = false}
打开App,查看更多内容
随时随地看视频慕课网APP