Set in golang

Go does not have set by default but there is way to imitate it in Go.

The following is an example code piece to create “set” in Go by setting a map with empty values.

$ cat test.go
package main

import (

// Main function
func main() {
    set := make(map[string]struct{})
    set["cat"] = struct{}{}
    set["dog"] = struct{}{}
    set["rabbit"] = struct{}{}

    if _, ok := set["rabbit"]; ok {
        fmt.Println("rabbit exists")


    if _, ok := set["rabbit"]; ok {
        fmt.Println("rabbit doesn't exist")

$ go run test.go
rabbit exists
rabbit doesn't exist