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
- Regex example to match multiline string in Rust?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use regex captures in Rust?
- How to use regex lookbehind in Rust?
- How to use modifiers in a Rust regex?
- How to replace all using regex in Rust?
- How to use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
See more codes...