好好爱自己!

golang type conversion

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.

posted @ 2019-05-06 22:01  立志做一个好的程序员  阅读(493)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处