Contents
NULL not supported
Rust does not support NULL unlike some other modern programming languages like Java. Actually, it does not have NULL or null keyword. However, it provides an enum Option used in similar way to Java 8 Optional.
Rust Enforces Variable Initialization
Rust enforces variable initialization both for “global” and “local” variables.
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 to the following two separate error messages.
Compile Error 1
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 |
Compile Error 2
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` |
Using Enum Option
Below is a short code snippet demonstrating how to use the enum Option.
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()); } |
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.37.0.
Summary
Since NULL or null is not supported, there is no need to check for NULL values in Rust.