package main import "fmt" func main() { var hashtable = make(map[string]int) hashtable["ABA"] = 13 hashtable["CAB"] = 12 hashtable["BAC"] = 15 fmt.Println(hashtable) i := hashtable["ABA"] fmt.Println("ABAs age is ",i) j := hashtable["BAC"] fmt.Println("BACs age is ",j) }
Luckily, Go already provides the map to deal with Hashtable.
So, in the above code, we have created a map named hashtable(That actually acts as a Hashtable).
var hashtable = make(map[string]int)
Then we have stored the names ABA, CAB and BAC and their corresponding ages 13, 12 and 15 in the Hashtable.
hashtable["ABA"] = 13 hashtable["CAB"] = 12 hashtable["BAC"] = 15
But how they are stored in the HashTable will be decided by Go. As we are using the map provided by Go.
So, for ABA, a Hash Code is calculated by Go and the age of ABA is stored in some location decided by Go.
Similarly, the age of CAB and BAC is stored in the Hashtable after Go calculates the Hash Code, and decides where they will be stored.
After all the values are stored, we then check all the values stored in the Hashtable.
fmt.Println(hashtable)
Then we try to retrieve the age of ABA.
i := hashtable["ABA"]
So, we pass the name of ABA and internally Go calculates the Hash Code for ABA and gives us the age of ABA from the Hashtable.
And we print the age of ABA on the screen.
fmt.Println("ABAs age is ",i)
Similarly we retrieve the age of BAC and print it on the screen.
j := hashtable["BAC"] fmt.Println("BACs age is ",j)