Nilness Analyzer Inspection
In today’s post, I want to look at a new code analysis tool that is introduced in the 2019.1 release of GoLand. It’s named Nilness Analyzer, and you can find it under Settings/Preferences | Editor | Inspections | Go | Probable bugs | Nilness analyzer.
This inspection helps us detect cases when we want to access information that could cause a panic, such as calling methods on a nil interface, using methods or members of nil structures, accessing nil slices, and so on.
Because this inspection is native to our IDEs, it will run as you type, which means that it will catch errors as soon as they are written, making it really quick during the development cycle to find issues, before even running a test suite or the application itself.
Let’s jump into some examples of cases it detects and how they look:
As you can see, the IDE tells us pretty quickly that we are trying to access an element from a slice that’s nil, which would result in a panic at runtime.
This works in more complex cases. For example, if you want to access a field of a variable which is a pointer and you don’t check the corresponding error for it, then this could also produce a runtime panic.
Cases like comparisons that will always be true or false can also be caught by the new inspection.
Ever wondered if you call a method on a nil pointer receiver?
Or when conditions might lead to a runtime panic because they test for the wrong nil value.
That’s it for today. I hope you like the new inspection.
Please let us know in the comments section below, on Twitter, or our issue tracker, about your thoughts on this, and what you would like to see from us in the future, be it feature request, article, or if you have any issues that would like to get fixed.