Is it possible to cast map[string]string to map[string]interface{} without using for loop in golang?

9.4k views Asked by At

When I try to convert map[string]string object to map[string]interface{} in golang using following snippet, I get an error.

package main

import "fmt"

func main() {
    var m = make(map[string]string)
    
    m["a"] = "b"
    
    m1 := map[string]interface{}(m)
    fmt.Println(m1)
}

I get an error like this :

# example
./prog.go:10:30: cannot convert m (type map[string]string) to type map[string]interface {}

I'm able to convert this using long for loop solution using following code, but I was wondering if there is any simpler approach to this.

package main

import (
    "fmt"
)

func main() {
    m := map[string]string{
        "a": "a",
        "b": "b",
    }

    m2 := make(map[string]interface{}, len(m))
    for k, v := range m {
        m2[k] = v
    }
    
    fmt.Println(m2) 
}

2

There are 2 answers

0
advay rajhansa On BEST ANSWER

There is no such thing as cast in go. There is type conversion only. So the best possible way is to use the loop and then convert string to interface.

2
Zombo On

You can roundtrip it through JSON:

package main

import (
   "bytes"
   "encoding/json"
   "fmt"
)

func transcode(in, out interface{}) {
   buf := new(bytes.Buffer)
   json.NewEncoder(buf).Encode(in)
   json.NewDecoder(buf).Decode(out)
}

func main() {
   m := map[string]string{"a": "b"}
   n := make(map[string]interface{})
   transcode(m, &n)
   fmt.Println(n) // map[a:b]
}

https://golang.org/pkg/encoding/json