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

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

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

问题

就像 PHP 中的 array_unique 函数一样:

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

输出结果:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

谢谢!

英文:

Just like array_unique function for php:

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

Output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Thx!

答案1

得分: 3

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

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

package main

import (
	"fmt"
)

func Unique(m map[string]string) map[string]string {
	n := make(map[string]string, len(m))
	ref := make(map[string]bool, len(m))
	for k, v := range m {
		if _, ok := ref[v]; !ok {
			ref[v] = true
			n[k] = v
		}
	}

	return n
}

func main() {
	input := map[string]string{"a": "green", "0": "red", "b": "green", "1": "blue", "2": "red"}
	unique := Unique(input)
	fmt.Println(unique)
}

可能的输出

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:

package main

import (
	"fmt"
)

func Unique(m map[string]string) map[string]string {
	n := make(map[string]string, len(m))
	ref := make(map[string]bool, len(m))
	for k, v := range m {
		if _, ok := ref[v]; !ok {
			ref[v] = true
			n[k] = v
		}
	}

	return n
}

func main() {
	input := map[string]string{"a": "green", "0": "red", "b": "green", "1": "blue", "2": "red"}
	unique := Unique(input)
	fmt.Println(unique)
}

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:

确定