DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

Go - Set structure

#go

Simple Set struct in Golang.

// 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
}
view raw set.go hosted with ❤ by GitHub

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay