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.

猜你喜欢

转载自www.cnblogs.com/oxspirt/p/10822441.html