How to represent a set
Sets in Go are usually represented with maps from the given type to a primitive value that defines its existence. The map
type is how you can semantically represent an unordered collection of unique elements.
var tileSet map[Tile]bool
Note that you can use non-pointer Tile
structs as map keys. because:
Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
...and clearly the two int
fields X
and Y
are comparable.
This is how you use such a map:
tileSet = make(map[Tile]bool, 0)
tile := Tile{X:1,Y:2}
tileSet[tile] = true
// check existence
if exists := tileSet[tile]; exists {
// ...
}
// range over set elements
for tile, _ := range tileSet {
// ...
}
How to represent a map of set
Trivially:
var tileSetMap map[string]map[Tile]bool
To simplify the code, you can also define your own set type:
type TileSet map[Tile]bool
and then
func main() {
var tileSetMap map[string]TileSet
// you initialize it normally with make
tileSetMap = make(map[string]TileSet, 0)
tileSetMap["foo"] = make(TileSet, 0)
tile := Tile{10, 20}
tileSetMap["foo"][tile] = true
fmt.Println(tileSetMap) // map[foo:map[{10 20}:true]]
}
Playground: https://play.golang.org/p/ObUo62SI3ih
[1] Specs: Map Types
The comparison operators == and != must be fully defined for operands of the key type