Documentation
¶
Overview ¶
Package orderedmap provides an implementation of ordered map.
An ordered map guarantees that the iteration order preserves the original insertion order. If an existing key is updated later, that doesn't change its iteration order. But if a key was deleted then later inserted again, the iteration order reflects its last insertion order.
Example ¶
package main import ( "fmt" "go.yhsif.com/orderedmap" ) func main() { var m orderedmap.Map[string, int] fmt.Println(m.Load("key1")) fmt.Println(m.LoadOrStore("key1", 1)) fmt.Println(m.LoadOrStore("key1", 2)) m.Store("key2", 2) fmt.Println(m.Load("key2")) m.Store("key1", 11) fmt.Println(m.Load("key1")) fmt.Println("Range1:") m.Range(func(k string, v int) bool { fmt.Println(k, v) return true }) m.Delete("key1") m.Store("key1", 1) fmt.Println("Range2:") m.Range(func(k string, v int) bool { fmt.Println(k, v) return true }) }
Output: 0 false 1 false 1 true 2 true 11 true Range1: key1 11 key2 2 Range2: key2 2 key1 1
Index ¶
- type Map
- func (m *Map[K, V]) All() func(yield func(K, V) bool)
- func (m *Map[K, V]) Delete(key K)
- func (m *Map[K, V]) Load(key K) (value V, ok bool)
- func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool)
- func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)
- func (m *Map[K, V]) Range(f func(key K, value V) bool)
- func (m *Map[K, V]) Store(key K, value V)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Map ¶
type Map[K comparable, V any] struct { // contains filtered or unexported fields }
Map represents an ordered map.
An ordered map preserves the inserting order when iterating.
Underlying it's wrapping a sync.Map with a doubly linked list.
The interface is intentionally kept almost the same with sync.Map to be used interchangeably.
The zero value is an empty map ready to use. A map must not be copied after first use.
func (*Map[K, V]) Load ¶
Load loads key from the map.
The ok result indicates whether the value is found in the map.
func (*Map[K, V]) LoadAndDelete ¶ added in v0.2.0
LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.
func (*Map[K, V]) LoadOrStore ¶
LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.