Simple Set
struct in Golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package collection provides collection data structure. | |
package collection | |
const ( | |
// Use as the stuffing data. | |
// Use "map" for implementing this struct but it does not use the value of map, | |
// so set dummy value to the map value. | |
_stuffing = 0 | |
) | |
// Set provides "set" structure. | |
type Set struct { | |
values map[interface{}]int | |
} | |
// NewSet creates new struct. | |
func NewSet() *Set { | |
set := &Set{} | |
set.values = make(map[interface{}]int) | |
return set | |
} | |
// Set sets value. | |
func (s *Set) Set(value interface{}) { | |
s.values[value] = _stuffing | |
} | |
// Remove removes value. | |
func (s *Set) Remove(value interface{}) { | |
if s.Contains(value) { | |
delete(s.values, value) | |
} | |
} | |
// Contains check if the value contains. | |
func (s Set) Contains(value interface{}) bool { | |
_, contain := s.values[value] | |
return contain | |
} |
Example
package collection_test
import (
"fmt"
"<Project>/collection"
)
func ExampleSet() {
s := collection.NewSet()
// Set values
s.Set("value1")
s.Set("value2")
// Check
fmt.Println(s.Contains("value1"))
fmt.Println(s.Contains("value2"))
// Remove
s.Remove("value2")
// Removed so does not exists.
fmt.Println(s.Contains("value2"))
// Output:
// true
// true
// false
}
Top comments (0)