Go的Set實現
Go的Set實現
- 由于Go的內置集合中沒有Set的實現,可以用map[type]struct{}
要求:
1、元素的唯一性
2、基本操作:添加、刪除、判斷是否存在、統計元素數量
3、可遍歷集合
//聲明Set
type Set struct {
//利用map,實現的Set集合
MapSet map[string]struct{}
}
//新增
func (s *Set) add(val string) {
s.MapSet[val] = struct{}{}
}
//刪除
func (s *Set) delete(val string) {
delete(s.MapSet, val)
}
//是否存在
func (s *Set) exist(val string) bool{
if _, ok :=s.MapSet[val]; !ok {
return false
}
return true
}
//計數
func (s *Set) count(val string) int {
return len(s.MapSet)
}
//遍歷:直接for遍歷s.MapSet
知止而后有定,定而后能靜,靜而后能安,安而后能慮,慮而后能得。
所謂誠其意者,毋自欺也。

浙公網安備 33010602011771號