Can I get a compile error on potential null ptr dereference – in Go?

A colleague has a null ptr dereference in Go.

I advised him to do as I would do – working in other languages, I tend to crank the warning level high and turn warnings into errors. In e.g. C#, that means I cannot compile this code:

private static string bad_deref(object? Object)
    return Object.ToString();

because I get

  x.cs(y,z): [CS8602] Dereference of a possibly null reference.

Which, to be clear, is very good.

But he tells me Go doesn’t have a warning level to crank and, googling, it would appear he is right.

So how do you solve this problem in Go? Are we back to good old C advice "good programmers don’t make mistakes" and null ptr dereferences just sometimes happen if you don’t work with perfect people?

>Solution :

That’s correct: you can’t make a compiler error out of dereferencing a pointer without handling a nil case. That’s because the language spec allows it. Nothing you can do about it.

You can write bad / incorrect code in any language, and the mean to detect errors early or mitigate them is to write tests in almost all languages.

Go has a nice testing framework built into the go tool itself. You should definitely take advantage of it. Write tests whenever / wherever appropriate. Go tests should be executed on a regular basis, they are automatically run during CI/CD and before releases. Most IDEs also run tests on save automatically.

Another trick you may use: if the nil pointer makes no sense, write an API that uses non-pointer type. Of course this has its drawbacks (sometimes pointers are a must); if using pointer makes more sense, use it, but check for nil values, and handle them properly (e.g. return an error, panic if that makes sense etc.). Also write tests to test with nil pointer values.

Leave a Reply