13.6 Practical Examples

13.6.1 Processing Data Streams

Example: Reading Lines from a File

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() -> io::Result<()> {
    let path = Path::new("numbers.txt");
    let file = File::open(&path)?;
    let lines = io::BufReader::new(file).lines();
    let sum: i32 = lines
        .filter_map(|line| line.ok())
        .filter(|line| !line.trim().is_empty())
        .map(|line| line.parse::<i32>().unwrap_or(0))
        .sum();
    println!("Sum of numbers: {}", sum);
    Ok(())
}

13.6.2 Implementing Functional Patterns

Example: Chaining Multiple Adapters

fn main() {
    let words = vec!["apple", "banana", "cherry", "date"];
    let long_uppercase_words: Vec<String> = words
        .iter()
        .filter(|word| word.len() > 5)
        .map(|word| word.to_uppercase())
        .collect();
    println!("{:?}", long_uppercase_words); // Output: ["BANANA", "CHERRY"]
}