doutao6330 2014-01-28 07: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 08: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.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名