How to convert type of map in golang
-
21-12-2019 - |
Question
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?
Solution
A different approach is to return T
not 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())
}
// 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.\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()))
}
OTHER TIPS
You can't. Those are completely different types. You have to copy and type cast item by item: 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())
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow