dictionary - 如何在golang中转换 map 类型

标签 dictionary go assertion

函数 B 返回类型 map[T][]T 如下所示:

type T interface{}

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

现在我有一个函数 A 调用函数 B,如下所示:

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
}

那么,我该如何制作这种覆盖类型的 map 呢?

最佳答案

你不能。这些是完全不同的类型。 您必须逐项复制并键入类型转换:http://play.golang.org/p/uhLPytbhpR

import "fmt"

type T interface{}

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

func A() map[string][]string {
    res := B()
    result := make(map[string][]string)
    for k,v := range res {
        key := k.(string)   
        value := make([]string, 0, len(res))
        for i := 0; i<len(value); i +=1 {
            value[i] = v[i].(string)
        }
        result[key]= value
    }
    return result
}

func main() {
    fmt.Println("Hello, playground", A())
}

关于dictionary - 如何在golang中转换 map 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050232/

相关文章:

go - 嵌套的 Gorilla Mux 路由器不工作

ruby - 在 rspec 中,为什么我不能在辅助类中使用 be_false 等?

java - java中如何从Map键中获取值

去旅游#5 : select statement example

c# - "An item with the same key has already been added"protobuf-net 错误

go - 如何在 golang 中使用 mux 和 gorm 发布 body raw?

python - 将多个变量断言为同一类型

c++ - Visual Studio regex_iterator 错误?

java - 数据结构集、列表、映射还是树?

python - 在 Pandas 数据框中存储字典