Skip to content

Instantly share code, notes, and snippets.

@grevych
Last active August 1, 2019 22:53
Show Gist options
  • Save grevych/f1fbd224d5d6c9d53af5cbe49a7fdd43 to your computer and use it in GitHub Desktop.
Save grevych/f1fbd224d5d6c9d53af5cbe49a7fdd43 to your computer and use it in GitHub Desktop.
Hash Map structure in Go. Link: https://goplay.space/#2XYw1W3ddUf
package main
import (
"errors"
"fmt"
)
type hash struct {
vector []interface{}
length int
capacity int
}
type Hash interface {
Insert(string, interface{}) error
Search(string) interface{}
Remove(string) error
Print()
}
func NewHash(capacity int) Hash {
h := &hash{
vector: make([]interface{}, capacity, capacity),
length: 0,
capacity: capacity,
}
return h
}
func (h *hash) hash(key string) int {
var index int
for _, rune := range key {
index += int(rune)
}
return index % h.capacity
}
func (h *hash) Insert(key string, value interface{}) error {
index := h.hash(key)
if h.vector[index] != nil {
return errors.New("Key already in use")
}
h.vector[index] = value
return nil
}
func (h *hash) Search(key string) interface{} {
index := h.hash(key)
return h.vector[index]
}
func (h *hash) Remove(key string) error {
index := h.hash(key)
if h.vector[index] == nil {
return errors.New("Key is not in use")
}
h.vector[index] = nil
return nil
}
func (h *hash) Print() {
for index, element := range h.vector {
if element == nil {
continue
}
fmt.Printf("%d -> %v\n", index, element)
}
}
func main() {
type Person struct {
name string
cellphone string
}
NewPerson := func(name, cellphone string) *Person {
return &Person{
name, cellphone,
}
}
hash := NewHash(500)
hash.Print()
fmt.Println("")
var person *Person
var err error
person = NewPerson("Gerardo", "4611021234")
err = hash.Insert(person.cellphone, person)
fmt.Println(err)
hash.Print()
fmt.Println()
person = NewPerson("Victor", "331204855")
err = hash.Insert(person.cellphone, person)
fmt.Println(err)
hash.Print()
fmt.Println()
p := hash.Search(person.cellphone)
fmt.Println(p)
fmt.Println()
err = hash.Remove(person.cellphone)
fmt.Println(err)
hash.Print()
fmt.Println()
person = NewPerson("Miguel", "331401855")
err = hash.Insert(person.cellphone, person)
fmt.Println(err)
hash.Print()
fmt.Println()
person = NewPerson("Existing", "331401855")
err = hash.Insert(person.cellphone, person)
fmt.Println(err)
hash.Print()
fmt.Println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment