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?

Heslacher
50.9k5 gold badges83 silver badges177 bronze badges
asked Nov 22, 2019 at 5:35
\$\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.

answered Nov 22, 2019 at 9:59
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.