1
0

refactor: use Result<T, E> instead of .unwrap()

This commit is contained in:
Rokas Puzonas 2021-12-03 00:43:29 +02:00
parent d34bc9a0f2
commit 85dd429a36
3 changed files with 17 additions and 6 deletions

View File

@ -2,6 +2,7 @@
https://adventofcode.com/2021
Error handling: http://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/error-handling.html#a-brief-interlude-unwrapping-isnt-evil
## Resources
* https://github.com/ithinuel/advent-of-code-rust/tree/2020/src/bin

View File

@ -1,13 +1,22 @@
use std::fs::File;
use std::io::prelude::*;
use std::io::{prelude::*, self};
use std::num::ParseIntError;
pub fn input_from_file(filename: &str) -> Vec<u32> {
let mut file = File::open(filename).expect("Can't open file");
#[derive(Debug)]
pub enum InputFromFileError {
ParseIntError(ParseIntError),
IoError(io::Error),
}
pub fn input_from_file(filename: &str) -> Result<Vec<u32>, InputFromFileError> {
let mut file = File::open(filename).map_err(InputFromFileError::IoError)?;
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Oops! Can not read the file...");
file.read_to_string(&mut contents).map_err(InputFromFileError::IoError)?;
return contents.split_whitespace().map(|s| s.parse::<u32>().unwrap()).collect();
contents.split_whitespace()
.map(|s| s.parse().map_err(InputFromFileError::ParseIntError))
.collect()
}
pub fn part1(depths: &[u32]) -> u32 {

View File

@ -2,7 +2,8 @@ mod day1;
fn main() {
let input_filename = "input.txt";
let input = day1::input_from_file(input_filename);
let input = day1::input_from_file(input_filename)
.expect("Failed to read input.txt");
let result1 = day1::part1(&input);
let result2 = day1::part2(&input);
println!("Part 1 result: {}", result1);