Error propagation is a core concept in Rust that allows you to handle errors in a clean and structured way. Instead of having to handle each error manually on every step, you can easily use the ?
operator to propagate errors to a higher level so that they can be handled in a single place.
In this challenge, you’ll use io::Error
to represent potential issues when working with file I/O. This approach leverages Rust’s standard library for concise and idiomatic error handling.
Your task is to implement a function that reads integers from a file, computes their sum, and gracefully propagates any errors using the ?
operator.
Implement the function sum_integers_from_file
:
Result<i32, io::Error>
.io::Error
.io::Error
with a meaningful message.?
operator.io::Error
with io::ErrorKind::InvalidData
.If you're stuck, here are some hints to help you solve the challenge:
std::fs::File::open
to open a file.io::BufReader::new
to read lines from the file.str::parse
method.io::Error::new
function can create custom errors.?
operator. e.g.
map_err
method. e.g.