Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return a Result type from the function.
Rust
fn divide(a: f64, b: f64) -> [1] { if b == 0.0 { Err("Cannot divide by zero") } else { Ok(a / b) } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
Option instead of Result when you want to provide error details.Returning just
f64 without error handling.✗ Incorrect
The function returns a Result type to handle success (Ok) and error (Err) cases properly.
2fill in blank
mediumComplete the code to propagate errors using the ? operator.
Rust
fn read_number_from_file() -> Result<i32, std::io::Error> {
let content = std::fs::read_to_string("number.txt")[1];
let num: i32 = content.trim().parse().unwrap();
Ok(num)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
.unwrap() which panics on error instead of propagating it.Using
.ok() which converts to Option and loses error info.✗ Incorrect
The ? operator propagates errors automatically, making error handling concise.
3fill in blank
hardFix the error in the match expression to handle both Ok and Err variants.
Rust
match result [1]{ Ok(value) => println!("Value: {}", value), Err(e) => println!("Error: {}", e), }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=>' after match instead of braces.
Using 'in' or 'with' which are invalid here.
✗ Incorrect
The match expression requires braces {} to enclose its arms.
4fill in blank
hardFill in the blank to create a custom error type implementing the Error trait.
Rust
#[derive(Debug)] struct MyError; impl std::fmt::Display for MyError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "An error occurred") } } impl std::error::[1] for MyError {{}} fn do_something() -> Result<(), MyError> { Err(MyError) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Implementing the wrong trait like
Clone or Copy.Forgetting to return
Err variant.✗ Incorrect
The custom error type must implement the Error trait. Returning Err(MyError) signals an error.
5fill in blank
hardFill all three blanks to use a Result with map_err to convert error types.
Rust
fn parse_number(s: &str) -> Result<i32, String> {
s.parse::<i32>()
.map_err(|[1]| [2]::from(format!("Parse error: {}", [3])))
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name in the closure.
Using an unrelated error type like
std::io::Error.✗ Incorrect
The closure argument e is used to create a new String error message with format!.