refactor: use Result<T, E> instead of .unwrap()
This commit is contained in:
parent
d34bc9a0f2
commit
85dd429a36
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
https://adventofcode.com/2021
|
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
|
## Resources
|
||||||
* https://github.com/ithinuel/advent-of-code-rust/tree/2020/src/bin
|
* https://github.com/ithinuel/advent-of-code-rust/tree/2020/src/bin
|
||||||
|
19
src/day1.rs
19
src/day1.rs
@ -1,13 +1,22 @@
|
|||||||
use std::fs::File;
|
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> {
|
#[derive(Debug)]
|
||||||
let mut file = File::open(filename).expect("Can't open file");
|
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();
|
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 {
|
pub fn part1(depths: &[u32]) -> u32 {
|
||||||
|
@ -2,7 +2,8 @@ mod day1;
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let input_filename = "input.txt";
|
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 result1 = day1::part1(&input);
|
||||||
let result2 = day1::part2(&input);
|
let result2 = day1::part2(&input);
|
||||||
println!("Part 1 result: {}", result1);
|
println!("Part 1 result: {}", result1);
|
||||||
|
Loading…
Reference in New Issue
Block a user