Sub topic 1
Why Rust Has No Null and No Exceptions
Prerequisites
This chapter assumes basic Rust syntax, enums, match, ownership, borrowing, and simple iterators. It also assumes you know that Option<T> and Result<T, E> are enums.
Why Rust Has No Null and No Exceptions
Rust does not use null for a missing value. A null value can cause a runtime error when code uses it as if it were present. Rust makes absence explicit in the type system.
Rust also does not use exceptions for ordinary failures. A function returns a value that describes success or failure. The caller must choose how to handle that value.
flowchart TD
A[Operation] --> B{What can happen?}
B -->|Value may be absent| C[Option T]
B -->|Operation may fail| D[Result T, E]
C --> E[Handle both variants]
D --> E`Option<T>`: A Value That May Be Missing
Option<T> has two variants:
Some(value)contains a value of typeT.Nonerepresents no value.
For example, a search can return Option<i32> instead of using a special number such as -1.
`Result<T, E>`: An Operation That May Fail
Result<T, E> represents either:
Ok(value), when the operation succeeds.Err(error), when it fails.
The E type describes the failure. Parsing text into a number is a common example:
fn parse_port(text: &str) -> Result<u16, std::num::ParseIntError> {
text.parse()
}
fn main() {
match parse_port("8080") {
Ok(port) => println!("port: {port}"),
Err(error) => println!("invalid port: {error}"),
}
}Handling Variants with `match`, `if let`, and `let else`
Use match when every case needs an explicit action. Use if let when you care about one variant. Use let else when failure should exit early.
fn label(value: Option<&str>) -> String {
let Some(text) = value else {
return String::from("missing");
};
if let Some(first) = text.chars().next() {
format!("starts with {first}")
} else {
String::from("empty")
}
}`unwrap` and `expect`: Shortcuts That Can Panic
unwrap() extracts a value from Some or Ok, but panics for None or Err. expect() does the same and adds a message. Use them only when failure is impossible or represents a programmer error. For input, files, networks, and other runtime conditions, return or handle the error instead.
Exercise
Which type should a lookup function return when no matching item is an expected outcome?
Show answer
Return Option<T>, using Some(item) for a match and None otherwise.