Search code examples
gotypestype-assertion

How to convert different values from map[string]interface{} to type string


I have a map with different types in interface{} and I need to convert them all to string type. Type assertion is not enough.

package main

func main() {
    map1 := map[string]interface{}{"str1": "string one", "int1": 123, "float1": 0.123}

    var slc []string
    for _, j := range map1 {
        slc = append(slc, j.(string)) // panic: interface conversion: interface {} is int, not string
    }
}

Solution

  • @Adrian and @Kaedys comments point to the correct answer. Developing it a bit more you could do something as:

    package main
    
    import "fmt"
    
    func main() {
        map1 := map[string]interface{}{"str1": "string one", "int1": 123, "float1": 0.123}
    
        var slc []string
        for _, j := range map1 {
            switch v := j.(type) {
            case string:
                slc = append(slc, v)
            case fmt.Stringer:
                slc = append(slc, v.String())
            default:
                slc = append(slc, fmt.Sprintf("%v", v))
            }
        }
    
        fmt.Println(slc)
    }
    

    This answer will work for strings, any type that implements the fmt.Stringer interface, and will default to fmt.Sprintf("%v", ...).