英文:
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]
注意
由于映射不保持顺序,你无法知道哪些键会被去除。
英文:
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]
Note
Because maps do not maintain order, you cannot know which keys will be stripped away.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论