du13932014807 2014-06-05 01:32
浏览 63
已采纳

如何在Golang中转换地图类型

The function B return type map[T][]T like this:

type T interface{}

func B() map[T][]T {
  result := make(map[T][]T)
  return result
}

And now I have a function A call function B like this:

func A() map[string][]string {
  res := B()
  return res.(map[string][]string) //I'm sure the type is map[string][]string,so I use assertion, but it doesn't works
}

So, how can I do this cover type of map?

  • 写回答

2条回答 默认 最新

  • dongxianghui3709 2014-06-05 02:11
    关注

    A different approach is to return T not map[T][]Tplay:

    type T interface{}
    
    func B() T {
        result := map[string][]string{
            "test": {"test", "test"},
        }
        return T(result)
    }
    
    func A() map[string][]string {
        res := B()
        if v, ok := res.(map[string][]string); ok {
            return v
        }
        return nil
    }
    
    func main() {
        fmt.Println("Hello, playground", A())
    }
    

    // Edit, converter function : http://play.golang.org/p/cW_PNTqauV

    func makeMap() map[T][]T {
        return map[T][]T{
            "test": {"test", "test"},
            "stuff": {"stuff", 1212, "stuff"},
            1: {10, 20},
        }
    }
    
    func convertMap(in map[T][]T) (out map[string][]string) {
        out = make(map[string][]string, len(in))
        for k, _ := range in {
            if ks, ok := k.(string); ok {
                v := in[k] // this way we won't use a copy in the for loop
                out[ks] = make([]string, 0, len(v))
                for i := range v {
                    if vs, ok := v[i].(string); ok {
                        out[ks] = append(out[ks], vs)
                    } else {
                        fmt.Printf("Error: %v (%T) is not a string.
    ", v[i], v[i])
                    }
    
                }
            } else {
                fmt.Printf("Error: %v (%T) is not a string.
    ", k, k)
            }
    
        }
        return
    }
    
    func main() {
        fmt.Println(convertMap(makeMap()))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集