rustUsing question mark errors in Rust
Rust uses the question mark operator (?) to handle errors in a concise and easy-to-read way. This operator is used to return a Result type, which can either be Ok or Err.
Code example:
fn main() {
let result = divide(4, 2);
match result {
Ok(val) => println!("Result: {}", val),
Err(e) => println!("Error: {}", e),
}
}
fn divide(x: i32, y: i32) -> Result<i32, &'static str> {
if y == 0 {
return Err("Cannot divide by 0");
}
Ok(x / y)
}
Output
Result: 2
Explanation:
fn main(): This is the main function, which is the entry point of the program.let result = divide(4, 2): This line calls thedividefunction with the arguments4and2.match result {: This line uses amatchexpression to check the result of thedividefunction.Ok(val) => println!("Result: {}", val): If the result isOk, this line prints the value ofval.Err(e) => println!("Error: {}", e): If the result isErr, this line prints the value ofe.fn divide(x: i32, y: i32) -> Result<i32, &'static str>: This is thedividefunction, which takes twoi32arguments and returns aResulttype.if y == 0 {: This line checks if the second argument is0.return Err("Cannot divide by 0"): If the second argument is0, this line returns anErrwith the messageCannot divide by 0.Ok(x / y): If the second argument is not0, this line returns anOkwith the result of the division.
Helpful links:
More of Rust
- How to add an entry to a Rust HashMap?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to make regex case insensitive in Rust?
- How to use regex lookahead in Rust?
- How to use binary regex in Rust?
- How to match all using regex in Rust?
- How to print a Rust HashMap?
- How to create a nested HashMap in Rust?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...