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 convert Rust bytes to a struct?
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- YAML serde example in Rust
- How to replace strings using Rust regex?
- How to declare a constant Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to create a HashMap of structs in Rust?
See more codes...