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 theDebugtrait for theErrorenum. This allows us to print out the error message when an error occurs. -
The
Errorenum is defined with three variants:NotFound,PermissionDenied, andConnectionError. -
The
mainfunction creates aResultwith anErrvariant containing theError::NotFoundvariant. -
The
println!macro is used to print out theResult, which will print out the error message.
Helpful links:
More of Rust
- Regex example to match multiline string in Rust?
- How to create a HashMap of HashMaps in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to perform matrix operations in Rust?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to split a string with Rust regex?
- How to use negation in Rust regex?
- How to use backslash in regex in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...