RustByExample.cn

Rust Result Error Handling Example

Overview

This example shows a common Rust pattern for Result. The goal is to keep the code small enough to understand while still being useful in real projects.

Code example

fn parse_port(input: &str) -> Result<u16, std::num::ParseIntError> {
    input.parse::<u16>()
}

fn main() {
    match parse_port("8080") {
        Ok(port) => println!("port: {}", port),
        Err(err) => eprintln!("error: {}", err),
    }
}

How it works

The example demonstrates how Rust combines strong typing with explicit ownership. Read the code from top to bottom and pay attention to where values are created, borrowed, moved, or consumed.

Common mistakes

  • Forgetting whether a method takes ownership or borrows a value.
  • Mixing references and owned values without clear intent.
  • Ignoring compiler notes that point to the exact line that caused the issue.

When to use this pattern

Use this pattern when you want clear, explicit Rust code that can be checked at compile time and maintained safely as the project grows.

Related examples

  • HashMap Example
  • Result Error Handling Example
  • Arc Mutex Example