Skip to content

maputil.SortByKey 问题 #307

@shijl0925

Description

@shijl0925

https://github.com/duke-git/lancet/blob/main/maputil/map.go#L457

请教下:
maputil.SortByKey 函数返回的map 在遍历时是无序的。不明白这个函数的作用是什么?
如果需要一个排序的列表,为啥不返回一个包含key value 的结构体切片呢?

type KV[K any, V any] struct {
	Key   K
	Value V
}

func SortByKey[K constraints.Ordered, V any](m map[K]V, less func(a, b K) bool) []KV[K, V] {
	result := make([]KV[K, V], 0, len(m))

	keys := Keys[K, V](m)
	//keys := make([]K, 0, len(m))
	//for _, k := range Keys[K, V](m) {
	//	keys = append(keys, k)
	//}
	sort.Slice(keys, func(i, j int) bool { return less(keys[i], keys[j]) })

	for _, k := range keys {
		result = append(result, KV[K, V]{Key: k, Value: m[k]})
	}

	return result
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions