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 calleddivide
that takes twoi32
parameters and returns aResult
type with ani32
type forOk
and a&'static str
type 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 anErr
with the message "Cannot divide by zero!". -
Ok(x / y)
: This returns anOk
with the result of the division of the two parameters.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...