{

Learn how to create a Set data structure with examples


This post covers Implementation of Set Data structure in go language with examples

How to create a Set in Golang?

Set is a general data structure that contains a collection of elements, does not allow duplicate elements. some programming languages like java has inbuilt Set support

In a Programming language, Set is a computer data structure implementation of mathematical finest concepts. Generally Set are an Unordered list and no duplicates. In Golang, We can use Map type to implement the Set type.

You can implement set using Map types.
Golang has no built-in support for set because of no generics available. We can write a custom code to write a Map Implementation.

Syntax:

var myset map[type]struct{} or  
var myset map[type]bool  

we can go with map[type]struct{} than a map[type]bool, the reason is empty struct takes 0 bytes, bool takes 1 byte of size in memory.

Key is a type of data you want to create

Struct{} is an empty struct that takes 0 bytes in size.

Like other data structures, set also operations - Create a set, iterate over those elements, add elements, delete elements, clear the set, size of the set, check element exists in a set.

We will see the basic functions of a set.

  • Create and Declaration of a set

For example, let us create an Empty Set with accept string values.

s1 := make(map[string]struct{})  

This is an empty set with a string key and empty struct - struct{}

  • Add the elements of Set

You can add the elements to set using add an element to map syntax map declare an empty struct, use this as a value in a set map and key as string

 var empty = struct{}{}  
    s1["one"] = empty  
    s1["two"] = empty  
    s1["three"] = empty  
    fmt.Println(s1)      // map[three:{} one:{} two:{}]  
    fmt.Println(len(s1)) // 3 

The above code adds three elements to the set Once data is added to the set, We will see iteration.

  • Iteration of elements of a Set

You can iterate elements of a set using for loop with a range form.

for v := range s1 {  
        fmt.Println(v)  
    } 

When you run the above code multiple times, the Order of the elements is not guaranteed, Output is as follows.

one  
two  
three  
  • Check if elements exist in a set

We can check elements in a set using two values expression using getting items from the map.

_, ok := s1["one"];

This returns two values first value is an empty struct, not required, so blank identifier(_) is used in place second parameters is a boolean value - if exists, ok=true is returned, ok=false is returned, if not exists.

  
if _, ok := s1["one"]; ok {  
        fmt.Println("exists in a set ") //  Element exists  
    }  
    if _, ok := s1["ten"]; ok {  
        fmt.Println("Not exists in a set.") //  Element not exists  
    }  

And the output is

exists in a set 
  • Delete an element of a set

You can use the delete() function of the map to remove elements from a set.

delete(s1, "one")  
    fmt.Println(len(s1)) // 2  

Set Example - Basic Operations

Here is a complete Set Example with all basic operations

package main  
  
import (  
    "fmt"  
)  
  
func main() {  
    s1 := make(map[string]struct{})  
    fmt.Println(s1) // map[]  
    //Adding elements to Set  
    var empty = struct{}{}  
    s1["one"] = empty  
    s1["two"] = empty  
    s1["three"] = empty  
    fmt.Println(s1)      // map[three:{} one:{} two:{}]  
    fmt.Println(len(s1)) // 3  
  
    for v := range s1 {  
        fmt.Println(v)  
    }  
  
    if _, ok := s1["one"]; ok {  
        fmt.Println("exists in a set ") //  Element exists  
    }  
    if _, ok := s1["ten"]; ok {  
        fmt.Println("Not exists in a set.") //  Element not exists  
    }  
    delete(s1, "one")  
    fmt.Println(len(s1)) // 2  
  
}  

Output is

map[]  
map[two:{} three:{} one:{}]  
3  
one  
two  
three  
exists in a set  
2  
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.