-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
1
  • 4
    you can define a map that has functionality of set like map[Tile]bool Commented Jul 6, 2021 at 10:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. I made some changes to the playground that you shared. play.golang.org/p/VBflnzqDRN4 Creating an Add function that creates the set when needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.