rustHow to downcast an error in Rust
Downcasting an error in Rust is done using the try_downcast_ref method from the std::error::Error trait. This method takes a reference to an Error trait object and attempts to downcast it to a concrete type. If successful, it returns a reference to the concrete type, otherwise it returns None.
Code example:
use std::error::Error;
fn downcast_error(err: &dyn Error) -> Option<&dyn std::fmt::Debug> {
err.downcast_ref::<&dyn std::fmt::Debug>()
}
fn main() {
let err = std::io::Error::new(std::io::ErrorKind::Other, "oh no!");
let downcast_err = downcast_error(&err);
println!("downcast_err = {:?}", downcast_err);
}
Output
downcast_err = None
Explanation:
use std::error::Error: This imports theErrortrait from thestd::errormodule.fn downcast_error(err: &dyn Error) -> Option<&dyn std::fmt::Debug>: This function takes a reference to anErrortrait object and attempts to downcast it to a concrete type.err.downcast_ref::<&dyn std::fmt::Debug>(): This is the method used to downcast the error. It takes a type parameter which is the type to which the error should be downcast.let err = std::io::Error::new(std::io::ErrorKind::Other, "oh no!"): This creates a newstd::io::Errorwith theErrorKind::Otherand the message "oh no!".let downcast_err = downcast_error(&err): This calls thedowncast_errorfunction with a reference to theerrobject.println!("downcast_err = {:?}", downcast_err): This prints the result of the downcast attempt.
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...