Dictionary 如何在戈兰转换地图类型

Dictionary 如何在戈兰转换地图类型,dictionary,go,assertion,Dictionary,Go,Assertion,函数B返回类型map[T][]T如下: type T interface{} func B() map[T][]T { result := make(map[T][]T) return result } 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,

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

type T interface{}

func B() map[T][]T {
  result := make(map[T][]T)
  return result
}
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
}
现在我有一个函数
a
调用函数
B
如下:

type T interface{}

func B() map[T][]T {
  result := make(map[T][]T)
  return result
}
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
}

那么,我该如何制作这种封面类型的地图呢?

你不能。这些是完全不同的类型。 您必须逐项复制并键入cast:

导入“fmt”
类型T接口{}
func B()映射[T][]T{
结果:=make(映射[T][]T)
返回结果
}
func A()映射[string][]字符串{
res:=B()
结果:=make(映射[string][]string)
对于k,v:=范围res{
键:=k.(字符串)
值:=make([]字符串,0,len(res))

对于i:=0;i另一种方法是返回
T
而不是
map[T][]T

//编辑,转换器功能:


有一个问题,这是唯一的方法吗?据我所知,是的。@fabrizioM:不是用
表示I:=0;I
而是用Go成语
表示I:=0;I。在这种情况下,更好的方法是用
表示I:=range value{}
。同意
i+=1
,但这是迭代数组的常用范围吗?我认为索引运算符更适合于小错误,您有
value:=make([]string,0,len(res))
,这使得
len(value)==0
,因此使用
value[i]
会引起恐慌,您可以使用
append
value:=make([]字符串,len(res))
。想一想,但是
结果
类型必须是map[T][]T,请参阅
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.\n", v[i], v[i])
                }

            }
        } else {
            fmt.Printf("Error: %v (%T) is not a string.\n", k, k)
        }

    }
    return
}

func main() {
    fmt.Println(convertMap(makeMap()))
}