Last week I talked about how to create your own errors. Expanding on that idea, here’s a trick I like to use: Constant errors!
Constants in Go are limited to simple underlying types: bool
, string
, and the numeric types.
If we create our own type, which both satisfies the error
interface, and has such an underlying type, we can then create constant error values:
type errString string
func (e errString) Error() string {
return string(e)
}
const ErrTooManyFrogs = errString("too many frogs")
Okay. Neat trick. But why?
It’s impossible to change the value of a constant. That’s why they’re called constants, after all! But variables can be modified.
import "io"
func init() {
io.EOF = errors.New("LOLWUT")
}
Now, I’ve never seen code that does that. I can’t imagine why anyone would want to do that, either, except maybe for nefarious purposes. But with a constant error, that’s impossible. So small win!
I rant a bit about exported error variables in a video I made a while back, too.