Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 630
Ruchit Patel Avatar asked Oct 20 '25 13:10

Ruchit Patel


1 Answers

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.

like image 105
advay rajhansa Avatar answered Oct 23 '25 09:10

advay rajhansa