0
0
Rustprogramming~10 mins

Handling errors with match 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 match on the Result and print "Success" if Ok.

Rust
let result: Result<i32, &str> = Ok(10);
match result {
    [1] => println!("Success"),
    Err(e) => println!("Error: {}", e),
}
Drag options to blanks, or click blank then click option'
AOk(10)
BOk
COk(value)
DOk(_)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Ok without parentheses causes a syntax error.
Using Ok(10) only matches if the value is exactly 10.
2fill in blank
medium

Complete the code to extract the error message from Err variant.

Rust
let result: Result<i32, &str> = Err("Failed");
match result {
    Ok(val) => println!("Value: {}", val),
    [1] => println!("Error: {}", err),
}
Drag options to blanks, or click blank then click option'
AErr(err)
BErr(e)
CErr(msg)
DErr(error)
Attempts:
3 left
💡 Hint
Common Mistakes
Binding to a variable name different from the one used in println! causes errors.
Using Err without a variable name causes a syntax error.
3fill in blank
hard

Fix the error in the match arms to handle both Ok and Err correctly.

Rust
let result: Result<i32, &str> = Ok(5);
match result {
    Ok(value) => println!("Value is {}", value),
    [1] => println!("Error occurred"),
}
Drag options to blanks, or click blank then click option'
AErr(_)
BErr
CErr(e)
DErr()
Attempts:
3 left
💡 Hint
Common Mistakes
Using Err without parentheses causes syntax errors.
Using Err(e) without using 'e' causes warnings.
4fill in blank
hard

Fill both blanks to match on Result and print the value or error message.

Rust
let result: Result<&str, &str> = Err("Not found");
match result {
    [1] => println!("Found: {}", val),
    [2] => println!("Error: {}", err),
}
Drag options to blanks, or click blank then click option'
AOk(val)
BOk(value)
CErr(err)
DErr(e)
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in match arms and println! causes errors.
Not binding variables causes inability to print values.
5fill in blank
hard

Fill all three blanks to create a match that handles Ok with a number, Err with a message, and a default case.

Rust
let result: Result<i32, &str> = Ok(42);
match result {
    [1] => println!("Number: {}", num),
    [2] => println!("Error: {}", msg),
    [3] => println!("Unknown result"),
}
Drag options to blanks, or click blank then click option'
AOk(num)
BErr(msg)
C_
DErr(e)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Err(e) instead of Err(msg) when msg is used in println! causes errors.
Omitting the default case causes match to be non-exhaustive.