What Is nil in Go

nil in Go has several meanings:

  • It is a predeclared identifier in Go, which means you can use it without declaring it.
  • It represents zero values (and default values) of some types in Go, including interface types, pointer types, slice types, map types, channel types, function types.

Using nil as Zero Values

nil represents zero values (and default values) of some types in Go.

Using nil in Comparison

Two nil Values of Two Different Types Are Not Comparable

Example:

Two nil Values of The Same Type May Not Be Comparable

Example:

Two nil Values of The Same Type Can Be Comparable Only When This Type Supports Comparision

Example:

Be Careful in nil Comparison When Interface Values Are Involved

The following code will not cause any compiler failure but the result is false other than true.

  • The non-interface value is converted to the type of the interface value before making the comparison with an interface value. In this example, (*int)(nil) is converted to an interface value with {type: *int, value: nil}.
  • Two nil interface values are equivalent only when they carry the same type. In this case, the converted interface value {type: *int, value: nil} has a concrete dynamic type but the other interface value has not. That is why the comparison result is false.

Summary

  • nil is and a pre-declared identifier that can be used to represent the zero values of some types in Go.
  • Be careful when using nil in comparison, especially when interface values are involved. You need to understand what you are comparing: types, or values, or both.
  • (a thing)(nil) may not equal to nil, depends on what that thing is (a pointer or an interface). This means nil is strong-typed even though nildoes not have a default type (sarcasm).

A software engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store