In this lesson, you will learn how to leverage Rust's type system to make illegal states unrepresentable, effectively eliminating the need for runtime validation checks.
The Problem: Runtime Validation
In many languages, we define data structures using primitive types like String or u32. This often forces us to scatter "defensive" code throughout our logic to ensure values remain valid—for example, checking if a User's age is within a specific range or ensuring a Percentage type never exceeds 100. If we rely on runtime checks, we risk missing an edge case, leading to logic bugs that only appear while the program is running.
The Solution: Encoding Invariants
In Rust, we can "encode" these invariants directly into the type definition. By wrapping our data in a struct and keeping the fields private, we force any consumer of our code to go through a constructor (like new()) that validates the data exactly once. Once the data is inside the type, the compiler guarantees it remains valid.
Example: Enforcing a Non-Empty String
Imagine a Username that cannot be empty. Instead of checking if username.is_empty() everywhere, we wrap it:
pub struct Username(String);
impl Username {
pub fn new(value: String) -> Result<Self, &'static str> {
if value.is_empty() {
Err("Username cannot be empty")
} else {
Ok(Username(value))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
By hiding the inner String and providing only an as_str() accessor, it becomes impossible for any part of your system to possess an "invalid" Username. You’ve shifted the burden of proof from the runtime (where you might forget a check) to the compiler (which refuses to compile if the invariant is violated).
This approach allows you to build complex systems where you can trust your data implicitly, drastically reducing the number of if/else error-handling blocks in your core logic.
Key Takeaway: By using private fields and controlled constructors, you can move validation from runtime checks to type-level guarantees, ensuring that invalid data simply cannot exist within your program.