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
x
of interface type and a typeT
, the primary expressionx.(T)
asserts that
x
is notnil
and that the value stored inx
is 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)
whereT
is a type andx
is 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