Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to propagate the error using the ? operator.
Rust
fn read_file() -> Result<String, std::io::Error> {
let content = std::fs::read_to_string("file.txt")[1];
Ok(content)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; instead of ? causes the error to be ignored and code to not compile.
Using ! is for macros, not error propagation.
✗ Incorrect
The ? operator propagates the error if read_to_string fails, otherwise returns the content.
2fill in blank
mediumComplete the code to propagate the error from parsing an integer using the ? operator.
Rust
fn parse_number(s: &str) -> Result<i32, std::num::ParseIntError> {
let num = s.parse::<i32>()[1];
Ok(num)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; ignores the error and causes a type mismatch.
Using ! is incorrect here.
✗ Incorrect
The ? operator propagates the parse error if parsing fails.
3fill in blank
hardFix the error in the code by correctly propagating the error with the ? operator.
Rust
fn open_and_read() -> Result<String, std::io::Error> {
let mut file = std::fs::File::open("data.txt")[1];
let mut buf = String::new();
std::io::Read::read_to_string(&mut file, &mut buf)?;
Ok(buf)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; causes a type mismatch error.
Using ! is invalid here.
✗ Incorrect
The ? operator propagates the error from File::open if it fails.
4fill in blank
hardFill both blanks to propagate errors correctly when opening and reading a file.
Rust
fn read_file_contents() -> Result<String, std::io::Error> {
let mut file = std::fs::File::open("input.txt")[1];
let mut contents = String::new();
file.read_to_string(&mut contents)[2];
Ok(contents)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; ignores errors and causes compile errors.
Using ! is incorrect for error propagation.
✗ Incorrect
Both File::open and read_to_string can fail, so both need ? to propagate errors.
5fill in blank
hardFill all three blanks to propagate errors correctly when opening, reading, and parsing a file.
Rust
fn read_and_parse() -> Result<i32, Box<dyn std::error::Error>> {
let mut file = std::fs::File::open("number.txt")[1];
let mut contents = String::new();
file.read_to_string(&mut contents)[2];
let number = contents.trim().parse::<i32>()[3];
Ok(number)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; causes errors to be ignored and compilation to fail.
Using ! is not for error propagation.
✗ Incorrect
All three operations can fail, so each needs ? to propagate errors properly.