### 簡單實現

``````// ListMap.go
package main

import "container/list"

// _listMapKV : 內部list.Element的Value
type _listMapKV[K string | int | uint, V any] struct {
k K
v V
}

type ListMap[K string | int | uint, V any] struct {
List *list.List
Map  map[K]*list.Element
}

// Init : 初始化，也可以用來清空
func (t *ListMap[K, V]) Init() *ListMap[K, V] {
t.List = new(list.List)
t.List.Init()
t.Map = make(map[K]*list.Element)
return t
}

// ListMapNew : 在堆中創建ListMap
func ListMapNew[K string | int, V any]() *ListMap[K, V] {
tmp := new(ListMap[K, V])
return tmp.Init()
}

// Put : 插入kv
func (t *ListMap[K, V]) Put(k K, v V) {
val, ok := t.Map[k]
s := _listMapKV[K, V]{}
s.k = k
s.v = v
if !ok {
e := t.List.PushBack(&s)
t.Map[k] = e
} else {
val.Value = &s
}
}

// Get : 按k獲得v
func (t *ListMap[K, V]) Get(k K) (v V, b bool) {
val, ok := t.Map[k]
b = ok
if ok {
v = val.Value.(*_listMapKV[K, V]).v
}
return
}

// Rm : 按k移除kv
func (t *ListMap[K, V]) Rm(k K) {
val, b := t.Map[k]
if b {
delete(t.Map, k)
t.List.Remove(val)
}
}

// Each 按插入順序循環全部kv
func (t *ListMap[K, V]) Each(f func(k K, v V)) {
e := t.List.Front()
for e != nil {
s := e.Value.(*_listMapKV[K, V])
f(s.k, s.v)
e = e.Next()
}
}
``````

### 使用

``````//main.go
package main

import "fmt"

func main() {
lm := ListMapNew[string, *string]()
k := "a"
v := "aaa"
lm.Put(k, &v)
vv, _ := lm.Get(k)
fmt.Println("get : ", vv, " -> ", *vv)
lm.Rm(k)
vv, ok := lm.Get(k)
fmt.Println("rm and get : ", vv, " ok: ", ok)
lm2 := ListMapNew[string, string]()
lm2.Put(k, v)
lm2.Each(func(k string, v string) {
fmt.Println("each : ", k, " : ", v)
})
lm2.Init()
vv2, ok := lm2.Get(k)
fmt.Println("rm and get2 : ", len(vv2), " k: ", ok)
}
``````