Module 6 • Lesson 31

The Result Type

📚 8 min💻 Free🦀 nixus.pro

The Result Type in Practice

use std::fs;
use std::io;

// Reading a file - returns Result
fn read_config(path: &str) -> Result {
    fs::read_to_string(path)
}

// Chain multiple Results
fn get_config_value(path: &str, key: &str) -> Result {
    let content = fs::read_to_string(path)
        .map_err(|e| format!("Cannot read {}: {}", path, e))?;

    for line in content.lines() {
        if let Some(val) = line.strip_prefix(&format!("{}=", key)) {
            return Ok(val.trim().to_string());
        }
    }
    Err(format!("Key '{}' not found", key))
}

fn main() {
    // Pattern matching
    match read_config("/etc/hostname") {
        Ok(content) => println!("Hostname: {}", content.trim()),
        Err(e) => println!("Error: {}", e),
    }

    // Transformations
    let doubled: Result = "21".parse::().map(|n| n * 2);
    println!("{:?}", doubled); // Ok(42)

    let checked: Result = "21".parse::()
        .and_then(|n| if n > 0 { Ok(n) } else { Err("must be positive".parse::().unwrap_err()) });

    // Collect Vec> into Result,E>
    let inputs = vec!["1", "2", "3"];
    let numbers: Result, _> = inputs.iter().map(|s| s.parse::()).collect();
    println!("{:?}", numbers); // Ok([1, 2, 3])
}

🎯 Practice

  1. Write fn read_number_from_file(path: &str) -> Result<i32, String> that reads a file and parses its content as i32
  2. Chain Result operations: parse a string, multiply by 2 if Ok, filter out negatives
  3. Use map_err to convert between error types

🎉 Key Takeaways