doutao6330 2014-01-27 23:49
浏览 98
已采纳

有没有一种方法可以为golang唯一地使用map [string] interface {}?

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条回答 默认 最新

  • duanjuete9206 2014-01-28 00:44
    关注

    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.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部