Tech TLDR;

  • Archive
  • Top Posts
  • GitHub
  • LinkedIn
  • Contact

Golang “Set” Data Structure Example

July 8, 2019 by admin

Golang does not have built it sets.

Basic functionality can be mimicked using maps with empty struct{}.

Another option is to use a Boolean value, but empty struct does not use any space and therefore more efficient. Another benefit of empty struct is that Boolean value can be set to true or false, which could be confusing in cases where we just want to check for key existence in a set (regardless of it’s value).

Bellow is a working basic implementation, you can also see it in Go Playground: https://play.golang.org/p/Lk63G8gNN_t.

package main

import "fmt"

func main() {

    // {} creates empty struct
    set := map[int]struct{}{1: {}, 2: {}, 3: {}}

    // Type of set[1] is struct {} aka empty struct
    fmt.Printf("Type of set[1] is %T aka empty struct\n", set[1])

    // Set hit example
    if _, found := set[1]; found {
        fmt.Println("1 is found")
    }

    // Set miss example
    if _, found := set[4]; !found {
        fmt.Println("4 is not found")
    }
}
Code language: JavaScript (javascript)

Filed Under: Golang

Copyright © 2025 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in