4
\$\begingroup\$

Preface: I am learning Rust through the Advent of Code

The task is to read lines from a file, parse each as an integer, then provide a summation of all the numbers. My solution looks like this:

use std::fs::File;
use std::io::{self, prelude::*, BufReader};

fn main() -> io::Result<()> {
    let file = File::open("day01.txt")?;
    let reader = BufReader::new(file);

    let mut sum: i32 = 0;

    for line in reader.lines() {
      let value: i32 = line.unwrap().parse().unwrap();
      sum += value
    }

    println!("{}", sum);

    Ok(())
}

I'd like to use the iterator methods map and sum in my solution, but I haven't figured out how to do so with the type checker. Suggestions?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

That's how you use Iterator::sum:

use std::fs::File;
use std::io::{self, prelude::*, BufReader};

fn main() -> io::Result<()> {
    let file = File::open("day01.txt")?;
    let reader = BufReader::new(file);
    let sum: i32 = reader
        .lines()
        .map(|line| line.unwrap().parse::<i32>().unwrap())
        .sum();

    println!("{}", sum);

    Ok(())
}

You must first say to what type the line must be parsed: parse::<i32>() and then, you must give the sum a type because the output of the Add trait is not the same as self and other.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.