3

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

Ruchit Patel
  • 733
  • 1
  • 11
  • 26
  • 4
    *"Is it possible to cast map[string]string to map[string]interface{} without using for loop in golang?"* -- Nope. A loop is as simple, and as idiomatic, as it gets. – mkopriva Apr 23 '21 at 10:01
  • 5
    See this entry in the [FAQ](https://golang.org/doc/faq#convert_slice_of_interface), it's about slices but it applies to maps equally. – mkopriva Apr 23 '21 at 10:02
  • Thanks @mkopriva for clarification and reference – Ruchit Patel Apr 23 '21 at 10:06

2 Answers2

8

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.

advay rajhansa
  • 1,129
  • 9
  • 17
-4

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

Zombo
  • 1
  • 62
  • 391
  • 407
  • 2
    it works, but this is a terrible idea. the loop will be a ton more efficient to execute, and to write. –  Apr 23 '21 at 18:39
  • 1
    The json package uses reflection under the covers. So it would be better to use reflection directly if you want to make a generic map converter. For a targeted conversion - a statically typed loop is best. – colm.anseo Apr 24 '21 at 13:00