Go Sets: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(One intermediate revision by the same user not shown)
Line 29: Line 29:
s.put("A") // s.contains("A") return true
s.put("A") // s.contains("A") return true
s.remove("A") // s.contains("A") return false
s.remove("A") // s.contains("A") return false
</syntaxhighlight>
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:
<syntaxhighlight lang='go'>
s := make(set) // s.contains("A") return false
updateSet(s)
s.contains("A") // returns true
func updateSet(s set) {
  s.put("A")
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 23:32, 28 August 2024

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")
}