Documentation ¶
Overview ¶
Package dictionary implements a hash/map/dictionary for educational purposes.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SetBuckets ¶
func SetBuckets(n uint32) func(d *Dictionary)
SetBuckets will set the number of hash buckets.
Example ¶
package main import ( "fmt" "github.com/bakins/dictionary" ) func main() { d := dictionary.New(dictionary.SetBuckets(997)) k := dictionary.StringKey("foo") d.Set(k, "bar") v, _ := d.Get(k) fmt.Println(v.(string)) }
Output: bar
Types ¶
type Dictionary ¶
type Dictionary struct {
// contains filtered or unexported fields
}
Dictionary is a simple hashed dictionary. It is intended to only store a single type, but does not enforce this explicitly. It is not safe for concurrent use, so users should implement their own locking.
func New ¶
func New(options ...OptionsFunc) *Dictionary
New creates a new dictionary. Options can be set by passing in OptionsFunc
Example ¶
package main import ( "fmt" "github.com/bakins/dictionary" ) func main() { d := dictionary.New() k := dictionary.StringKey("foo") d.Set(k, "bar") v, _ := d.Get(k) fmt.Println(v.(string)) }
Output: bar
func (*Dictionary) Delete ¶
func (d *Dictionary) Delete(key Hasher) (interface{}, bool)
Delete removes an item from the dictionary. Returns the deleted value.
func (*Dictionary) Each ¶
func (d *Dictionary) Each(f EachFunc) error
Each executes the function on each element. Error returned will be any error the EachFunc returned to stop iteration
func (*Dictionary) Get ¶
func (d *Dictionary) Get(key Hasher) (interface{}, bool)
Get returns an item from the dictionary. The second return value will be false if not found.
func (*Dictionary) Keys ¶
func (d *Dictionary) Keys() []Hasher
Keys returns all the keys in the hash
func (*Dictionary) Set ¶
func (d *Dictionary) Set(key Hasher, val interface{})
Set adds an item to the dictionary. It will replace any existing value.
type EachFunc ¶
EachFunc is the function called on each element when calling Each returning a non-nil error will cause iteration to stop
type Hasher ¶
type Hasher interface { // Hash should return a hash of the key. Ideally, this should create // a good distribution and avoid collisions. Hash() uint32 // Equal must return true if the receiver is equal to the argument. Equal(interface{}) bool }
Hasher defines interface for keys to be stored in a dictionary.
type OptionsFunc ¶
type OptionsFunc func(*Dictionary)
OptionsFunc is used to set options when creating a new dictionary.