Skip to content
项目

关于

🔃 Go 有序映射,Set、Get、Delete 和 Len 操作的摊销复杂度为 O(1)。

学习与教育

这些数字如何统计

实测星标增长

24小时
0
7天
+1
15天
0
1个月
+3

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

🔃 github.com/elliotchance/orderedmap/v3 GoDoc

Basic Usage

An *OrderedMap is a high performance map that preserves the insertion order of keys. Keys are not sorted. Set, Get, Delete and Len have amortized O(1) time complexity:

import "github.com/elliotchance/orderedmap/v3"

func main() {
	m := orderedmap.NewOrderedMap[string, any]()

	m.Set("foo", "bar")
	m.Set("qux", 1.23)
	m.Set("123", true)

	m.Delete("qux")
}

[!NOTE]

  • v3 requires Go v1.23 - If you need to support Go 1.18-1.22, you can use v2.
  • v2 requires Go v1.18 for generics - If you need to support Go 1.17 or below, you can use v1.

Internally an *OrderedMap uses the composite type map combined with a trimmed down linked list to maintain the order.

Iterating

The following methods all return iterators that can be used to loop over elements in an ordered map:

  • AllFromFront()
  • AllFromBack()
  • Keys()
  • Values()

The examples below use the map created in Basic Usage:

// Iterate through all elements from oldest to newest:
for key, value := range m.AllFromFront() {
	fmt.Println(key, value)
}
// foo bar
// 123 true

These range loops stop after the last element yielded by the iterator. If the map is changing while the iteration is in-flight it may produce unexpected behavior.

If you want to get a slice of the map keys or values, you can use the standard slices.Collect method with the iterator returned from Keys() or Values():

fmt.Println(slices.Collect(m.Keys()))
// [foo 123]

Likewise, calling maps.Collect on the iterator returned from AllFromFront() will create a regular unordered map from the ordered one:

fmt.Println(maps.Collect(m.AllFromFront()))
// map[123:true foo:bar]

If you don't want to use iterators, you can also manually loop over the elements using Front() with Next(), or Back() with Prev(). These element pointers become nil beyond the last or first element, respectively. Front() and Back() return nil when the map is empty:

// Iterate through all elements from oldest to newest:
for el := m.Front(); el != nil; el = el.Next() {
    fmt.Println(el.Key, el.Value)
}

// You can also use Back and Prev to iterate in reverse:
for el := m.Back(); el != nil; el = el.Prev() {
    fmt.Println(el.Key, el.Value)
}

探索相关项目

加载中…