-2

I would like to know how to define a map of sets in Go. A set is a collection of unordered unique elements.

The sets are collections of a struct (Tile). The key of the map is a string. The key is the combination of tile.X + "," + tile.Y.

What I have so far. It only works for one element, not a set.

type Tile struct {
    X int
    Y int
}

func (t Tile) GetKey() {
    return strconv.Itoa(t.X) + "," + strconv.Itoa(t.Y)
}

// This only works for one element, not for a set.
type Cache map[string]Tile
blackgreen
  • 34,072
  • 23
  • 111
  • 129
jordiburgos
  • 5,964
  • 4
  • 46
  • 80

1 Answers1

1

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

blackgreen
  • 34,072
  • 23
  • 111
  • 129
  • 1
    Nice. I made some changes to the playground that you shared. https://play.golang.org/p/VBflnzqDRN4 Creating an Add function that creates the set when needed. – jordiburgos Jul 08 '21 at 16:00