Published on

Smart Casting in Go


Today I was reading an excellent article about how to manage error handling in GoLang. One code example demonstrated the correct way to safely cast from one type to another. In the article the author had created a custom interface for errors that enriched custom errors he created with additional information. He would smart cast this using the following code:

if ierr, ok := err.(*imgproxyError); ok {
} else {
    msg := fmt.Sprintf("Unexpected error: %s", err)
    respondWithError(&imgproxyError{500, msg, "Internal error"})

You essentially use the ok variable to check if the cast happened successfully or not. The author has a nice example that shows the difference between a safe cast and an unsafe cast:

// Unsafe. If err is not *imgproxyError, Go will panic.
ierr := err.(*imgproxyError)

// Safe way. ok indicates if interface was typecast successfully or not.
// Go will not panic even if the interface represents the wrong type.
ierr, ok := err.(*imgproxyError)

This article was most enlightening in seeing different approaches to error handling in Go as well as seeing some of the idiomatic Go ways of doing things.