DEV Community

Cover image for Creating a hashmap from scratch in Golang
Victor Hugo
Victor Hugo

Posted on

Creating a hashmap from scratch in Golang

Recently I was watching this video from a Brazilian youtuber called Augusto Galego about creating a hashmap from scratch, while I was watching this video something came to my mind: what if I do the same but with go? and that is what I did! here is the repo If you want to try, in the main file there is a lot of tests with the hashmap, you will need to have installed go version 1.18 or superior because of the go generics.

  • first you will need to copy the code on your machine, check if you have installed git on it:
git clone https://github.com/hxsggsz/hashmap-go.git
Enter fullscreen mode Exit fullscreen mode
  • now run the main.gofile to see the tests:
go run main.go
Enter fullscreen mode Exit fullscreen mode

What is a hashmap

A hashmap is a data structure that stores key-value pairs. It uses a hash function to compute an index where the value is stored, enabling average O(1) time complexity for insertions, deletions, and lookups, so for example, if you want to store some data in the key "age" it will hash this key, this will generate a large number, we get this large number and divide it by the factorial of the size of your data structure, in my case I use the slices from Golang, it will returns always the same number by the length of the key, this will be the index to search in the data structure. But what if I store two values with a key with the same index?

For example I store the value 21 in key age and 200 in key now, the hash function will return the same index for both of the keys because both of them have the same size of characters, that's a conflict problem and to solve this I use the chaining solution that consists in using another slice inside the slice to store the values, so for example in the index 3 of the slice it will have another slice with key age and value 21 and the key now with the value 200.

Methods

This hashmap have 4 public methods:

  • set
    • store a key with a value.
    • if there already have key stored, he updates the value.
  • get
    • gets the value stored to a key.
    • if not founds the key it throws a error.
  • put
    • update the value stored to a key.
    • if not founds the key it throws a error.
  • delete
    • deletes the value and key stored to a key.
    • if not founds the key it throws a error.

And on private method:

  • hash:
    • hashs the string passed by param and divide by factorial of the size of the slice.

Generics

I am a typescript developer and I love using generics in my code, because of that I saw an opportunity to learn to use generics on Golang, since it was implemented in the version >1.18, and that is what I did, instead of allowing only a type of data in the hashmap I use the generics to allow any type of the data in the hashmap.

Top comments (0)