Go Sets: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 5: Line 5:


A set can be implemented as a map with value type <code>bool</code>. Set the map entry to <code>true</code> to put the value in the set and then test it by simple indexing.
A set can be implemented as a map with value type <code>bool</code>. Set the map entry to <code>true</code> to put the value in the set and then test it by simple indexing.
=Implementation=
<syntaxhighlight lang='go'>
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]
}
</syntaxhighlight>
<syntaxhighlight lang='go'>
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
</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>

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