Member-only story
Avoiding Common Rust Mistakes: Sentinel Values and Effective Enums
surrounded by floating bats, dancing ghosts, and intricately woven spider webs. The composition includes small stars and a moon symbol, adding an eerie glow to the design. Isolated on a white background. Created using: Adobe Illustrator, thin and thick strokes, intricate linework, playful curves, clean vector paths, precise detailing, gothic-inspired font with a modern twist, strong contrast for a bold appearance.
As popularity of Rust is gaining traction in the programming community, developers — especially those transitioning from other languages — one might encounter some common pitfalls. In the following writing I am going to take on two key mistakes that new Rust developers often make: using sentinel values instead of leveraging Rust’s powerful enums and not utilizing enums effectively. Both issues can lead to less readable, maintainable, and idiomatic code. Let’s explore how Rust offers better alternatives and how you can improve your coding practices by avoiding these mistakes.
Mistake 1: Using Sentinel Values Instead of Option Enum
What is the Issue?
Sentinel values are special values used in place of actual data to indicate a condition like “no value” or “error” While this approach is common in languages like C, it can lead to unclear code, making it harder to understand what special values represent. This also opens the door to subtle bugs.
Let’s consider the following example using sentinel values:
fn get_age_from_input(input: i32) -> i32 {
if input >= 0 {
input
} else {
-1 // Sentinel value indicating an invalid age
}
}