Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Cast type fails for map[string]interface{} to map[string]string

Tags:

casting

go

I wasn't sure why the following casting doesn't work:

import "fmt"

func main() {
    v := map[string]interface{}{"hello": "world"}
    checkCast(v)

}

func checkCast(v interface{}) {
    _, isCorrectType := v.(map[string]string)
    if !isCorrectType { 
        fmt.Printf("incorrect type")  <------------- why does it enter this if statement?
        return
    }
}
like image 200
Karan Avatar asked Feb 13 '23 14:02

Karan


1 Answers


map[string]interface{} is not the same as map[string]string. Type interface{} is not the same as type string.

If they are both map[string]string:

package main

import "fmt"

func main() {
    v := map[string]string{"hello": "world"}
    checkCast(v)

}

func checkCast(v interface{}) {
    _, isCorrectType := v.(map[string]string)
    if !isCorrectType {
        fmt.Printf("incorrect type")
        return
    }
}

Output:

[no output]

The statement v.(map[string]string) is a type assertion, not a cast.

The Go Programming Language Specification

Type assertions

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.


Go has conversions.

The Go Programming Language Specification

Conversions

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

like image 97
peterSO Avatar answered Mar 24 '23 07:03

peterSO