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 to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...