Go Sets

From NovaOrdis Knowledge Base
Revision as of 23:27, 28 August 2024 by Ovidiu (talk | contribs) (→‎Overview)
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