0
0
Rustprogramming~10 mins

Propagating errors with ? in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A?
B;
C!
D.
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.
2fill in blank
medium

Complete 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'
A!
B.
C?
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; ignores the error and causes a type mismatch.
Using ! is incorrect here.
3fill in blank
hard

Fix 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'
A?
B;
C!
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; causes a type mismatch error.
Using ! is invalid here.
4fill in blank
hard

Fill 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'
A?
B;
C!
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; ignores errors and causes compile errors.
Using ! is incorrect for error propagation.
5fill in blank
hard

Fill 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'
A?
B;
C!
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using ; causes errors to be ignored and compilation to fail.
Using ! is not for error propagation.