从具有广义类型参数的映射中返回顶级键。

huangapple go评论71阅读模式
英文:

Return top level keys from map with a generalised type argument

问题

我有以下方法,它返回map中的所有键。但是它接受的参数必须是map[string]string类型。

func GetAllKeys(m map[string]string) []string {
	keys := make([]string, len(m))
	i := 0
	for k := range m {
		keys[i] = k
		i++
	}

	return keys
}

如果我有一个类型为map[string]map[string]stringmap,我该如何重用这个方法呢?有没有一种通用的方法,因为它只需要返回顶层键。

英文:

I have the following method which returns all the keys from the map. But the argument it accepts must be of type map[string]string.

func GetAllKeys(m map[string]string) []string {
	keys := make([]string, len(m))
	i := 0
	for k := range m {
		keys[i] = k
		i++
	}

	return keys
}

How could I reuse this method, if I have a map but with a type map[string]map[string]string. Is there a way to generalize this method, because all it has to do is return the top-level keys from the map.

答案1

得分: 0

使用Go 1.18+,你可以使用类型参数编写通用函数。以下是一个示例:

func GetAllKeys[K comparable, V any](m map[K]V) []K {
	keys := make([]K, len(m))
	i := 0
	for k := range m {
		keys[i] = k
		i++
	}
	return keys
}

你可以在这里查看示例代码的运行结果。

英文:

With Go 1.18+ you can write generic functions with type parameters:

func GetAllKeys[K comparable, V any](m map[K]V) []K {
	keys := make([]K, len(m))
	i := 0
	for k := range m {
		keys[i] = k
		i++
	}
	return keys
}

https://go.dev/play/p/jV2eNKjZmZu

huangapple
  • 本文由 发表于 2023年3月5日 14:01:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75640476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定