Golang - safe cast
Lets say you have an interface in Golang, and for some reason you want to cast it.
How do we do that?
var myVar interface{}
...
myVar = secondVar.(string)
But what happens when myVar is not a string?
Well, this happens:
panic: interface conversion: interface is int, not string
The program does a panic and the whole executable exits and shutdown.
Luckily, there is a safe / safer way to avoid system panic when casting in GoLang:
var firstVar interface{}
firstVar = "this is a string"
firstString, ok := firstVar.(string)
if (!ok) {
fmt.Printf("firstString is not a string, do something about it! Value:'%v'\n", firstString)
}
Now, if its not a string, an message will be printed in the console or you can input a default value for it.
Lets create a small test code to check the result:
var firstVar interface{}
var secondVar interface{}
secondVar = 10
firstVar = "this is a string"
firstString, ok := firstVar.(string)
if (!ok) {
fmt.Printf("firstString is not a string, do something about it! Value:'%v'\n", firstString)
}
secondString, ok := secondVar.(string)
if (!ok) {
fmt.Printf("secondString is not a string, do something about it! Value:'%v'\n", secondString)
}
And the output is:
secondString is not a string, do something about it! Value:''
The code
Check the sample code in: https://github.com/mussatto/golab/tree/master/cast