Rust, Software Development

Rust – How to check for NULL values

Rust does not support NULL; therefore, we don’t perform NULL checks on values. It does not even have keywords for NULL. However, it provides an enum Option that we can use similarly to Java 8 Optional.

No NULL Check because Rust Enforces Variable Initialization

Rust enforces variable initialization both for “global” and “local” variables. As a result, all variables in our Rust codes require initial values. Consider the following codes.

These codes result in the following two separate error messages. The first error looks something like the following.

The second error gives an idea of some local variables with no initial value.

In Rust, using Enum Option is the closest we get to using NULL

Below is a short code snippet demonstrating how to use the enum Option. We can use the None enum to represent no-value, and that’s the closest we can get to using NULL in Rust. Instead of Rust codes to check for NULL values, we code to check for the None enum.

When we run these codes, we get the following output.

Tested with Rust 1.53.0.


We cannot make Rust check for NULL values because the language does not support the concept of NULL. Moreover, every variable in Rust requires initialization. However, we could use the Enum Option with None to represent a no-value.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like