0
0
Rustprogramming~5 mins

Handling errors with match in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the match statement do when handling errors in Rust?
It checks the result of an operation and lets you handle different cases, like Ok for success and Err for errors, by matching on these variants.
Click to reveal answer
beginner
How do you access the value inside an Ok variant using match?
You use a pattern like Ok(value) in the match arm to get the successful result stored in value.
Click to reveal answer
beginner
What is the purpose of the Err(e) pattern in a match statement?
It catches the error case and lets you handle or report the error stored in e.
Click to reveal answer
intermediate
Why is using match for error handling better than just unwrapping?
Because match lets you handle errors gracefully without crashing the program, unlike unwrap() which panics on errors.
Click to reveal answer
beginner
Write a simple match statement to handle a Result<String, &str> that prints the string on success or prints the error message on failure.
let result: Result<String, &str> = Ok("Hello".to_string());

match result {
    Ok(text) => println!("Success: {}", text),
    Err(e) => println!("Error: {}", e),
}
Click to reveal answer
What does match do when used with a Result type in Rust?
AIt ignores errors silently.
BIt automatically fixes errors.
CIt converts errors into success values.
DIt lets you handle both success and error cases separately.
Which pattern matches the error variant in a Result?
AOk(value)
BSome(value)
CErr(e)
DNone
What happens if you use unwrap() on an Err value?
APanics and crashes the program.
BConverts error to success automatically.
CIgnores the error and continues.
DReturns the error value.
In a match statement, how do you bind the success value of a Result to a variable?
AOk(value)
BErr(value)
CSome(value)
DNone
Why is handling errors with match considered good practice?
ABecause it hides errors from users.
BBecause it forces you to handle all possible cases explicitly.
CBecause it makes the program run faster.
DBecause it automatically fixes bugs.
Explain how to use match to handle a Result in Rust.
Think about how you separate success and error cases.
You got /5 concepts.
    Describe why using match for error handling is safer than using unwrap().
    Consider what happens when an error occurs.
    You got /4 concepts.