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
}
}
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 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
Conversions are expressions of the form
T(x)
whereT
is a type andx
is an expression that can be converted to typeT
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With