? Operator 🎯Welcome to our Rust tutorial! Today, we're going to delve into the world of the ? operator. This operator is a game-changer in Rust and will help you write cleaner, more efficient code. Let's get started!
? Operator: An Introduction 📝The ? operator, also known as the Result's unwrap method, is a powerful tool in Rust. It is used to handle error values when dealing with Result types.
let result = Some(5);
let number = result?.squared();
fn squared(value: i32) -> i32 {
value * value
}In this example, we have a Some value containing the number 5. We use the ? operator to unwrap this value and pass it to the squared() function, which returns the squared value.
? Operator: Error Handling 💡But what happens when we have an error? Let's take a look at a more complex example:
let result = match Some(5) {
Some(value) => Ok(value),
None => Err("No value present."),
};
let number = result?;
fn squared(value: i32) -> Result<i32, &'static str> {
if value < 0 {
Err("Number must be non-negative.")
} else {
Ok(value * value)
}
}In this example, we've added a possibility of error to the squared() function. If the input is negative, an error is returned. When we unwrap the Result with the ? operator, the error is propagated if present.
The ? operator can be chained, making your error handling cleaner and easier to read.
Use the expect() method for debugging during development, but remember to remove it before shipping your code.
Always ensure that your functions return a Result when they can potentially fail.
What does the `?` operator do in Rust?
That's it for today's Rust tutorial! We hope you found this introduction to the ? operator helpful. Stay tuned for more Rust tutorials, and remember to keep coding! ✅