Ben Chuanlong Du's Blog

It is never too late to learn.

Ordered Map in Golang

Tips & Traps

There are 2 implementations of ordered map in Golang orderedmap and go-ordered-map . orderedmap is more popular (based on GitHub statistics) and thus is preferred.

In [1]:
import "github.com/elliotchance/orderedmap/v2"
error executing "/usr/local/go/bin/go build -buildmode=plugin" in directory "/home/dclong/go/src/gomacro.imports/gomacro_pid_7244/import_1": exit status 2
In [3]:
var m OrderedMap[string, any]
repl.go:1:17: expected ';', found '['
In [5]:
m := orderedmap.NewOrderedMap[string, any]()
m
repl.go:1:37: expected ']', found ','
In [ ]:
	m.Set("foo", "bar")
	m.Set("qux", 1.23)
	m.Set("123", true)

	m.Delete("qux")
In [ ]:
m := orderedmap.NewOrderedMap[string, any]()

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

	m.Delete("qux")

References

https://github.com/golang/go/issues/27179 encoding/json: no way to preserve the order of map keys

In [ ]:
 

Comments