This is a creation in Article, where the information may have evolved or changed.
Golang and common operation of chain list, data Structure series original: Flaviocopes.com, translation has been authorized by the author.
Overview
A hash table is a map key-value pair stored in the same way as a type (an associative array in PHP) whose hash function calculates the position (index) of key in the array based on the key value.
Distinguish between the hash table and the Golang map, and the associative array in PHP:
Realize
Common operations
Use the built-in map types to implement the hash table and implement the following common operations:
1 2 3 4
|
Put () Remove () Get () Size ()
|
Similarly, create a generic type ValueHashTable to be the structure type of the hash table, where the key value implements the Stringer interface.
Code implementation
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + A at - - - - - in - to + - the * $ Panax Notoginseng - the + A the + - $ $ - - the - Wuyi the - Wu - About $ - -
|
Package Hashtable
Import ( "Github.com/cheekybits/genny/generic" "Sync" "FMT" )
type Key generic. Type type Value generic. Type
type valuehashtable struct { Items Map[int]value lock Sync. Rwmutex }
//Use Horner rules to generate a hash value for key in O (n) Complexity func hash(k Key) int { key: = Fmt. Sprintf ("%s", K) hash: = 0 For i: = 0; i < Len(key); i++ { hash = *hash + int(key[i]) } return hash }
//New key value func (HT *valuehashtable) Put(k Key, v Value) { Ht.lock.Lock () defer ht.lock.Unlock () h: = hash (k) if ht.items = = Nil { Ht.items = make (map[int]value) } Ht.items[h] = v }
//Delete key func (HT *valuehashtable) Remove(k Key) { Ht.lock.Lock () defer ht.lock.Unlock () h: = hash (k) Delete(Ht.items, h) }
//Gets the hash value of the key func (HT *valuehashtable) Get(k Key) Value { Ht.lock.RLock () defer ht.lock.RUnlock () h: = hash (k) return ht.items[h] }
//Get the size of the hash table func (HT *valuehashtable) Size() int { Ht.lock.RLock () defer ht.lock.RUnlock () return len(ht.items) }
|
Test Case: Hashtable_test.go