rustHow to derive error in Rust
Error handling in Rust is done using the Result
type, which is an enum that can either be Ok
or Err
. To derive an error in Rust, you can use the #[derive(Debug)]
attribute on a struct or enum. This will allow you to print out the error message when an error occurs.
Code example:
#[derive(Debug)]
enum Error {
NotFound,
PermissionDenied,
ConnectionError,
}
fn main() {
let result = Err(Error::NotFound);
println!("{:?}", result);
}
Output
Err(Error::NotFound)
Explanation:
-
The
#[derive(Debug)]
attribute is used to enable theDebug
trait for theError
enum. This allows us to print out the error message when an error occurs. -
The
Error
enum is defined with three variants:NotFound
,PermissionDenied
, andConnectionError
. -
The
main
function creates aResult
with anErr
variant containing theError::NotFound
variant. -
The
println!
macro is used to print out theResult
, which will print out the error message.
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...