Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type DefaultFactory ¶
type DefaultFactory[D any] func() D
DefaultFactory generates default values to be used with the Map.
type Map ¶
type Map[K comparable, V any] struct { // contains filtered or unexported fields }
Map will return a set default when attempting to get a value that wasn't inserted.
Example ¶
m := defaultmap.NewMap[string](func() string { return "I'm the default!" }) m.Insert("exists", "Hello, World!") fmt.Println(m.Get("exists")) fmt.Println(m.Get("doesn't exist")) fmt.Println(m.GetOr("also doesn't exist", "I'm a one-time default!"))
Output: Hello, World! I'm the default! I'm a one-time default!
func NewMap ¶
func NewMap[K comparable, V any](factory DefaultFactory[V]) Map[K, V]
NewMap generates a new map with that returns default values for keys that have not been set.
func (Map[K, V]) Contains ¶
Contains checks if the key exists in the map without creating a key-value pair using the DefaultFactory.
Example ¶
m := defaultmap.NewMap[string](func() string { return "I'm the default!" }) m.Insert("exists", "Hello, World!") fmt.Println(m.Contains("exists")) fmt.Println(m.Contains("doesn't exist"))
Output: true false
func (Map[K, V]) Delete ¶
func (m Map[K, V]) Delete(key K)
Delete removes a key-value pair from the map. This will cause the default value to be returned instead on attempts to access the value assigned to the key.
func (Map[K, V]) Get ¶
func (m Map[K, V]) Get(key K) V
Get tries to get the value mapped to the key, but will assign the return value from the DefaultFactory and return that instead if the key didn't exist.
Example ¶
m := defaultmap.NewMap[string](func() string { return "I'm the default!" }) m.Insert("exists", "Hello, World!") fmt.Println(m.Get("exists")) fmt.Println(m.Contains("doesn't exist")) fmt.Println(m.Get("doesn't exist")) fmt.Println(m.Contains("doesn't exist"))
Output: Hello, World! false I'm the default! true
func (Map[K, V]) GetOr ¶
func (m Map[K, V]) GetOr(key K, defaultValue V) V
GetOr allows you to specify the default value instead of using the DefaultFactory. Unlike Get, this will not assign the default if the key did not exist.
Example ¶
m := defaultmap.NewMap[string](func() string { return "I'm the default!" }) m.Insert("exists", "Hello, World!") fmt.Println(m.GetOr("exists", "other default")) fmt.Println(m.Contains("doesn't exist")) fmt.Println(m.GetOr("doesn't exist", "other default")) fmt.Println(m.Contains("doesn't exist"))
Output: Hello, World! false other default false