14.7 Practical Examples
14.7.1 Handling Missing Data
Scenario: Parsing user input that may or may not contain valid integers.
use std::io; fn parse_number(input: &str) -> Option<i32> { input.trim().parse::<i32>().ok() } fn main() { let inputs = vec!["42", " ", "100", "abc"]; for input in inputs { match parse_number(input) { Some(num) => println!("Parsed number: {}", num), None => println!("Invalid input: '{}'", input), } } }
Output:
Parsed number: 42
Invalid input: ' '
Parsed number: 100
Invalid input: 'abc'
14.7.2 Implementing Safe APIs with Option
Scenario: Designing a function that retrieves configuration settings, which may or may not be set.
struct Config { database_url: Option<String>, port: Option<u16>, } impl Config { fn new() -> Self { Config { database_url: None, port: Some(8080), } } fn get_database_url(&self) -> Option<&String> { self.database_url.as_ref() } fn get_port(&self) -> Option<u16> { self.port } } fn main() { let config = Config::new(); match config.get_database_url() { Some(url) => println!("Database URL: {}", url), None => println!("Database URL not set"), } match config.get_port() { Some(port) => println!("Server running on port: {}", port), None => println!("Port not set, using default"), } }
Output:
Database URL not set
Server running on port: 8080