GoTip #3 – Nil pointer methods handling

Couple of days ago I realized that Go has a neat feature when calling methods on nil pointers. But let’s start for the example. Let’s say that we have some code that calls a unicorn for us:

@@@go
unicorn, err := CallUnicorn()
if err != nil {
        fmt.Println("There're no unicorns around :/")
        return
}
unicorn.RideToTheRainbow()

Simple and straightforward. But let’s say that we’re calling unicorns in many places of our code. Then we’d have to repeat this error checking everywhere in order to not panic when unicorn didn’t shown up. That sucks a bit, we don’t like to repeat ourselves, right? So let’s do the trick.

@@@go
func (self *Unicorn) RideToTheRainbow() {
        if self != nil {
                // implement unicorn riding here...
        }    
}

Now we can do something like this, explicitly:

@@@go
var unicorn *Unicorn = nil
unicorn.RideToTheRainbow()

We know what’s the type of unicorn, we know what methods it can receive and so we can call them, since they’re pointer methods. The self parameter is a pointer, so we can check if it’s present or not. It’s a behavior similar to what we can achieve in pseudo object oriented programming in C, you can find something like this pretty often (I haven’t writing C for quite a while and I’m too lazy to test it so it may be wrong, but you get the idea):

@@@cpp
void 
unicorn_ride_to_the_rainbow(void *self) 
{
    if (self) {
        // implement unicorn riding...
    }
}

There’s no much more to say, so I’m leaving you with the picture of a lamacorn riding to the rainbow. Have a nice weekend folks!

Lamacorn

Comments

blog comments powered by Disqus