Starter lesson
Parse a value with an explicit result
Parsing can fail, so Rust represents the outcome as a Result. The caller must handle either the parsed value or the error.
fn parse_port(text: &str) -> Result<u16, std::num::ParseIntError> {
text.parse::<u16>()
}
fn main() {
match parse_port("8080") {
Ok(port) => println!("Listening on {port}"),
Err(error) => eprintln!("Invalid port: {error}"),
}
}
What to expect
Listening on 8080
Key idea: Make failure explicit in the return type and handle it where the application can respond appropriately.