Go Sets: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
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>

Revision as of 23:27, 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