How do I write a generic ordered map in Go?

Go, Generic, Ordered Map, Data Structure
Learn how to implement a generic ordered map in Go, allowing you to maintain the order of elements while using different data types.
package main import ( "fmt" "sync" ) // GenericOrderedMap defines a structure for a generic ordered map type GenericOrderedMap[K comparable, V any] struct { mu sync.RWMutex items []struct { key K value V } } // NewGenericOrderedMap initializes a new ordered map func NewGenericOrderedMap[K comparable, V any]() *GenericOrderedMap[K, V] { return &GenericOrderedMap[K, V]{} } // Put inserts the key-value pair into the map func (m *GenericOrderedMap[K, V]) Put(key K, value V) { m.mu.Lock() defer m.mu.Unlock() m.items = append(m.items, struct { key K value V }{key, value}) } // Get retrieves the value for a key func (m *GenericOrderedMap[K, V]) Get(key K) (V, bool) { m.mu.RLock() defer m.mu.RUnlock() for _, item := range m.items { if item.key == key { return item.value, true } } var zeroValue V return zeroValue, false } // Main function to demonstrate usage func main() { orderedMap := NewGenericOrderedMap[string, int]() orderedMap.Put("one", 1) orderedMap.Put("two", 2) if val, ok := orderedMap.Get("one"); ok { fmt.Println("Key: one, Value:", val) } }

Go Generic Ordered Map Data Structure