Recall & Review
beginner
What does the
? operator do in Rust?It checks if a function returned an error. If there is an error, it returns it immediately from the current function. Otherwise, it continues with the successful value.
Click to reveal answer
beginner
How does
? help with error propagation?It lets you write less code by automatically returning errors up the call stack without needing explicit
match or if let statements.Click to reveal answer
intermediate
Can
? be used in functions that do not return a Result or Option?No. The function must return a compatible type like
Result or Option for ? to work.Click to reveal answer
beginner
Example: What does this code do?<br><pre>let file = std::fs::File::open("foo.txt")?;</pre>It tries to open the file "foo.txt". If it fails, the error is returned from the current function immediately. If it succeeds, the file handle is stored in
file.Click to reveal answer
intermediate
Why is using
? considered more readable than manual error handling?Because it reduces nested code and boilerplate, making the main logic clearer and easier to follow.
Click to reveal answer
What happens when
? encounters an error in a Result?✗ Incorrect
The
? operator returns the error immediately from the current function, propagating it up.Which return types are compatible with using
??✗ Incorrect
? works with Result and Option types to propagate errors or None values.What is the main benefit of using
? in Rust?✗ Incorrect
? reduces the need for explicit error checks, making code cleaner and easier to read.Can you use
? inside a function that returns void (unit type)?✗ Incorrect
? requires the function to return a compatible type like Result or Option.What does this code do?<br>
let content = std::fs::read_to_string("file.txt")?;✗ Incorrect
It tries to read the file content. If it fails, the error is returned immediately using
?.Explain how the
? operator helps with error propagation in Rust.Think about how errors move up the call stack without extra code.
You got /4 concepts.
Describe a simple example where using
? makes your Rust code easier to read.Imagine you want to open a file and return an error if it fails.
You got /4 concepts.