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 thedivide
function with the arguments4
and2
.match result {
: This line uses amatch
expression to check the result of thedivide
function.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 thedivide
function, which takes twoi32
arguments and returns aResult
type.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 anErr
with the messageCannot divide by 0
.Ok(x / y)
: If the second argument is not0
, this line returns anOk
with the result of the division.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...