Go Sets
Jump to navigation
Jump to search
Internal
Overview
A set can be implemented as a map with value type bool
. Set the map entry to true
to put the value in the set and then test it by simple indexing.
Implementation
type set map[string]bool
func (s set) put(k string) {
s[k] = true
}
func (s set) remove(k string) {
s[k] = false
}
func (s set) contains(k string) bool {
return s[k]
}
s := make(set) // s.contains("A") return false
s.put("A") // s.contains("A") return true
s.put("A") // s.contains("A") return true
s.remove("A") // s.contains("A") return false
Sets implemented like this are passed by value, like the maps, but the set handles share the underlying storage, so a set passed to a function reflects changes applied to the set outside the function, and the changes applied to the set inside the function are visible outside the function:
s := make(set) // s.contains("A") return false
updateSet(s)
s.contains("A") // returns true
func updateSet(s set) {
s.put("A")
}