如何在golang中转换地图类型

时间:2014-06-05 01:32:46

标签: map 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
}

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

2 个答案:

答案 0 :(得分:2)

你做不到。那些是完全不同的类型。 您必须按项目复制并输入项目: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())
}

答案 1 :(得分:2)

另一种方法是返回T而不是map[T][]T play

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())
}

//编辑,转换器功能: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.\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()))
}