Golang Set Data Structure Implementation

In this post, we will learn how to implement Set data structure in Golang with an example.

A Set is a linear data structure that has a collection of values that are not repeated. A set can store unique values without any particular order. In the real world, sets can be used to collect all tags for blog posts and conversation participants in a chat. The data can be of Boolean, integer, float, characters, and other types. 

Golang Set Data Structure Implementation


package main

// importing fmt package
import (
	"fmt"
)

//Set class
type Set struct {
	integerMap map[int]bool
}

//create the map of integer and bool
func (set *Set) New() {
	set.integerMap = make(map[int]bool)
}

// adds the element to the set
func (set *Set) AddElement(element int) {
	if !set.ContainsElement(element) {
		set.integerMap[element] = true
	}
}

//deletes the element from the set
func (set *Set) DeleteElement(element int) {

	delete(set.integerMap, element)
}

//checks if element is in the set
func (set *Set) ContainsElement(element int) bool {
	var exists bool
	_, exists = set.integerMap[element]

	return exists
}

// main method
func main() {

	var set *Set
	set = &Set{}

	set.New()

	set.AddElement(1)
	set.AddElement(2)

	fmt.Println("initial set", set)
	fmt.Println(set.ContainsElement(1))

}

The main() method creates Set, invokes the New() method, and adds elements 1 and 2. The check is done if element 1 exists in the set.

Output:

initial set &{map[1:true 2:true]}
true

Comments