14.7 Practical Examples
This section presents practical examples that demonstrate how Rust’s type system and error-handling mechanisms help write safe and robust code. The examples focus on handling missing data, designing safe APIs, and leveraging Rust’s ownership and borrowing model to prevent common programming errors. These examples illustrate real-world scenarios where Rust’s approach improves reliability and maintainability.
14.7.1 Handling Missing Data from User Input
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 Designing Safe APIs
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