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
For an expression
xof interface type and a typeT, the primary expressionx.(T)asserts that
xis notniland that the value stored inxis of typeT. The notationx.(T)is called a type assertion.
Go has conversions.
The Go Programming Language Specification
Conversions are expressions of the form
T(x)whereTis a type andxis an expression that can be converted to typeT.
-
is there a way to cast in Go? – Karan Jul 4 '14 at 19:56
-
1@Karan: See my revised answer. Go has conversions. – peterSO Jul 4 '14 at 20:05

浙公网安备 33010602011771号