rustHow to define error in Rust
Error in Rust is defined using the Result type, which is an enum that can either be Ok or Err. Ok is used to indicate success, while 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)
}
Output
Result<i32, &'static str>
Explanation of code parts:
-
fn divide(x: i32, y: i32) -> Result<i32, &'static str>: This defines a function calleddividethat takes twoi32parameters and returns aResulttype with ani32type forOkand a&'static strtype forErr. -
if y == 0 { return Err("Cannot divide by zero!"); }: This checks if the second parameter is equal to zero, and if it is, it returns anErrwith the message "Cannot divide by zero!". -
Ok(x / y): This returns anOkwith the result of the division of the two parameters.
Helpful links:
More of Rust
- How to perform matrix operations in Rust?
- How to match whitespace with a regex in Rust?
- How to use regex lookahead in Rust?
- How to use regex to match a double quote in Rust?
- How to use a Rust HashMap in a struct?
- How to print the keys of a Rust HashMap?
- How to sort a Rust HashMap?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- Yield example in Rust
See more codes...