Go programming language is easy to learn, but there are some tricky traps. This article series is trying to show these booby traps so that you avoid them.
Type assertions might be a bit tricky sometimes:
package main
import "fmt"
func main() {
var data interface{} = "string"
if cast, ok := data.(int); ok {
fmt.Printf("%v is an int\n", cast)
} else {
fmt.Printf("%v is not an int\n", cast)
}
}
When we run this, we get:
$ go run broken.go
0 is not an int
Why is that? How could we fix it?
Expression cast, ok := data.(int)
performs a type assertion. Which means:
data
into an int
cast
is set with the int
value and ok
is true
cast
is set with int
zero value and ok
is false
Thus, as data
is not an integer, ok
is false
and cast
is set with 0 and it is not set with string
value of data.
We can fix performing another cast, as follows:
package main
import "fmt"
func main() {
var data interface{} = "string"
if cast, ok := data.(int); ok {
fmt.Printf("%v is an int\n", cast)
} else {
str := data.(string)
fmt.Printf("%v is not an int\n", str)
}
}
Enjoy!