如何使用Go实现BitSet? [英] How to implement BitSet with Go?
问题描述
我没有在Go中找到BitSet包,所以我试图实现它。
我想用一个uint64数组来存储这些位。
我需要分配uint64数组的位数。
使用Java,我可以定义一个带有整数的构造函数。
虽然Go没有提供构造函数,但当用户调用new()时,如何正确地初始化
BitSet的'对象'?
类型bitSet结构{
len int
array [] uint64
}
暴露接口BitSet:
类型BitSet接口{
Has(pos int)bool
Add(pos int)bool
Len )int
}
另外公开一个函数NewBitSet:
func NewBitSet(len int)BitSet {
return& bitSet {len,make(uint64,(len + 7)/ 8)}
$ b 这是一种封装的Go方式:共享一个接口,而不是实现。 p>
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()?
解决方案 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.
这篇关于如何使用Go实现BitSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!