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 replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use regex captures in Rust?
- How to use binary regex in Rust?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to lock a Rust HashMap?
- How to compare two Rust HashMaps?
- How to convert a Rust slice of u8 to a string?
- How to iterate over a Rust HashMap?
See more codes...