rustHow to return error in Rust
Rust provides a number of ways to return errors. The most common way is to use the Result
type. Result
is an enum that can either be Ok
or Err
. Ok
is used to indicate success and Err
is used to indicate an error.
Code example:
fn divide(x: i32, y: i32) -> Result<i32, &'static str> {
if y == 0 {
return Err("Cannot divide by zero!");
}
Ok(x / y)
}
fn main() {
let result = divide(10, 0);
match result {
Ok(val) => println!("Result: {}", val),
Err(err) => println!("Error: {}", err),
}
}
Output
Error: Cannot divide by zero!
Explanation:
- The
divide
function takes twoi32
parameters and returns aResult
type. TheResult
type is an enum that can either beOk
orErr
. - If the second parameter is 0, the function returns an
Err
with the message "Cannot divide by zero!". - If the second parameter is not 0, the function returns an
Ok
with the result of the division. - In the
main
function, the result of thedivide
function is stored in theresult
variable. - The
match
statement is used to check the value of theresult
variable. - If the
result
isOk
, the value is printed. - If the
result
isErr
, the error message is printed.
Helpful links:
More of Rust
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to clear a Rust HashMap?
- Yield example in Rust
- Example of yield_now in Rust?
- How to convert a Rust slice to a fixed array?
- How to use regex to match a group in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to yield a thread in Rust?
- How to replace strings using Rust regex?
See more codes...