Here is the simple implementation of set
We can define the interface as
type Set interface {
Add(data interface{})
Delete(data interface{}) bool
Contains(data interface{}) bool
Size() int
ToArray() []interface{}
Print()
}
lets define a type which implements our Set interface,
type set struct {
mymap map[interface{}]struct{}
empty struct{}
}
the map is the actual data holder here.
here is the implementation for the Set interface method.
func NewSet() Set {
return &set{mymap: make(map[interface{}]struct{})}
}
func (this *set) Add(data interface{}) {
this.mymap[data] = this.empty
}
// there may be a better approach
func (this *set) Delete(data interface{}) bool {
_, ok := this.mymap[data]
if ok {
delete(this.mymap, data)
}
return ok
}
func (this *set) Contains(data interface{}) bool {
_, ok := this.mymap[data]
return ok
}
func (this *set) Size() int {
return len(this.mymap)
}
func (this *set) ToArray() []interface{} {
size := len(this.mymap)
arr := make([]interface{}, size)
i := 0
for k, _ := range this.mymap {
arr[i] = k
i++
}
return arr
}
No comments:
Post a Comment