有没有一种方法可以为 golang 中的 map[string]interface{} 实现去重?

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

Is there a way to unique a map[string]interface{} for golang?

问题

就像 PHP 中的 array_unique 函数一样:

  1. $input = array("a" => "green", "red", "b" => "green", "blue", "red");
  2. $result = array_unique($input);
  3. print_r($result);

输出结果:

  1. Array
  2. (
  3. [a] => green
  4. [0] => red
  5. [1] => blue
  6. )

谢谢!

英文:

Just like array_unique function for php:

  1. $input = array("a" => "green", "red", "b" => "green", "blue", "red");
  2. $result = array_unique($input);
  3. print_r($result);

Output:

  1. Array
  2. (
  3. [a] => green
  4. [0] => red
  5. [1] => blue
  6. )

Thx!

答案1

得分: 3

没有内置的方法来实现这个功能,所以你需要自己编写一个函数。

如果你想要创建一个通用的函数,你需要使用reflect。如果你有一个特定的映射类型,那么你可以更容易地实现它:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func Unique(m map[string]string) map[string]string {
  6. n := make(map[string]string, len(m))
  7. ref := make(map[string]bool, len(m))
  8. for k, v := range m {
  9. if _, ok := ref[v]; !ok {
  10. ref[v] = true
  11. n[k] = v
  12. }
  13. }
  14. return n
  15. }
  16. func main() {
  17. input := map[string]string{"a": "green", "0": "red", "b": "green", "1": "blue", "2": "red"}
  18. unique := Unique(input)
  19. fmt.Println(unique)
  20. }

可能的输出

map[a:green 0:red 1:blue]

Playground

注意

由于映射不保持顺序,你无法知道哪些键会被去除。

英文:

There is no built in way to do it, so you need to make a function yourself.

If you want to make a general function, you will have to use reflect. If you have a specific map type, then you can make it more easily:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func Unique(m map[string]string) map[string]string {
  6. n := make(map[string]string, len(m))
  7. ref := make(map[string]bool, len(m))
  8. for k, v := range m {
  9. if _, ok := ref[v]; !ok {
  10. ref[v] = true
  11. n[k] = v
  12. }
  13. }
  14. return n
  15. }
  16. func main() {
  17. input := map[string]string{"a": "green", "0": "red", "b": "green", "1": "blue", "2": "red"}
  18. unique := Unique(input)
  19. fmt.Println(unique)
  20. }

Possible output

>map[a:green 0:red 1:blue]

Playground

Note

Because maps do not maintain order, you cannot know which keys will be stripped away.

huangapple
  • 本文由 发表于 2014年1月28日 15:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/21399728.html
匿名

发表评论

匿名网友

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

确定