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 use regex lookahead in Rust?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
- How to match whitespace with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to use non-capturing groups in Rust regex?
See more codes...