Complete the code to define a custom error enum named MyError.
#[derive(Debug)] enum MyError { [1] }
The enum variant Error(String) defines a custom error variant holding a string message.
Complete the code to implement the Display trait for MyError.
impl std::fmt::Display for MyError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { MyError::Error(msg) => write!(f, [1], msg), } } }
The format string "{}" directly prints the error message string.
Fix the error in the From trait implementation to convert std::io::Error into MyError.
impl From<std::io::Error> for MyError { fn from(err: std::io::Error) -> MyError { MyError::[1](err.to_string()) } }
The variant Error holds a String, so we convert the io::Error to string and wrap it.
Fill in the blank to implement the std::error::Error trait for MyError.
impl std::error::Error for MyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { [1] } }
Some(self) in source which causes lifetime issuesThe source method returns None because this error has no underlying cause.
Fill all three blanks to create a function that returns a Result with MyError and uses the ? operator.
fn read_file(path: &str) -> Result<String, MyError> {
let content = std::fs::read_to_string(path)[1];
Ok([2])
}
fn main() {
match read_file("file.txt") {
Ok(data) => println!("File content: {}", [3]),
Err(e) => println!("Error: {}", e),
}
}.unwrap() which panics on errorThe ? operator propagates errors. The variable content holds the file data, and data is used in the print statement.