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.
1 2 3 4 5 6 7 8 9 10 11 12 | // Global variable static MAX_THREADS: i32; fn main() { // Local variable let message:&str; print!("{}", message); print!("{}", MAX_THREADS); } |
These codes result in the following two separate error messages. The first error looks something like the following.
1 2 3 4 5 | error: expected one of `!`, `(`, `+`, `::`, `<`, or `=`, found `;` --> src\main.rs:1:24 | 1 | static MAX_THREADS: i32; | ^ expected one of `!`, `(`, `+`, `::`, `<`, or `=` here |
The second error gives an idea of some local variables with no initial value.
1 2 3 4 5 | error[E0381]: borrow of possibly uninitialized variable: `message` --> src\main.rs:9:18 | 9 | print!("{}", message); | ^^^^^^^ use of possibly uninitialized `message` |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fn main() { let recipient:Option<&str> = None; let message:Option<&str> = Some("Rust is an awesome programming language"); print!("Has recipient? {}\n", recipient.is_some()); print!("Has no recipient? {}\n", recipient.is_none()); print!("Has message? {}\n", message.is_some()); print!("Has no message? {}\n", message.is_none()); // This causes runtime error // print!("Recipient: {}\n", recipient.unwrap()); print!("Message: {}\n", message.unwrap()); } |
When we run these codes, we get the following output.
1 2 3 4 5 6 7 8 9 10 | C:/Users/karldev/.cargo/bin/cargo.exe run --color=always --package rust-project1 --bin rust-project1 Finished dev [unoptimized + debuginfo] target(s) in 0.03s Running `target\debug\rust-project1.exe` Has recipient? false Has no recipient? true Has message? true Has no message? false Message: Rust is an awesome programming language Process finished with exit code 0 |
Tested with Rust 1.53.0.
Summary
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.