alexkras.com

  • Home
  • Top Posts
  • Resume
  • Projects
  • YouTube
  • Boots to Bytes
  • About
  • Contact

Golang “Set” Data Structure Example

July 8, 2019 by Alex Kras Leave a Comment

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")
    }
}

Filed Under: Golang

I work for Evernote and we are hiring!

Subscribe to this Blog via Email

New posts only. No other messages will be sent.

You can find me on LinkedIn, GitHub, Twitter or Facebook.

This blog is moving to techtldr.com

Leave a Reply Cancel reply

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