Search code examples
gogo-interface

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


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


Solution

  • 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.