Last active
November 7, 2023 05:29
-
-
Save gustavocd/a4982df8a157af6b56bd364cf8436302 to your computer and use it in GitHub Desktop.
Simple Set in Go
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 main | |
import ( | |
"fmt" | |
) | |
func main() { | |
s := NewSet() | |
s.Add(1) | |
s.Add(1) | |
s.Add(1) | |
s.Add(2) | |
s.Add(3) | |
s.Add(3) | |
s.Add(1) | |
fmt.Println(s.values) | |
fmt.Println(s.Has(1)) | |
} | |
type Set struct { | |
values map[any]bool | |
} | |
func NewSet() *Set { | |
return &Set{values: make(map[any]bool)} | |
} | |
func (s *Set) Add(v any) { | |
s.values[v] = true | |
} | |
func (s *Set) Has(v any) bool { | |
_, ok := s.values[v] | |
return ok | |
} | |
func (s *Set) Delete(v any) { | |
delete(s.values, v) | |
} | |
// Playground: https://play.golang.com/p/sg3Kglu8c5t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment