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 theError
trait from thestd::error
module.fn downcast_error(err: &dyn Error) -> Option<&dyn std::fmt::Debug>
: This function takes a reference to anError
trait 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::Error
with theErrorKind::Other
and the message "oh no!".let downcast_err = downcast_error(&err)
: This calls thedowncast_error
function with a reference to theerr
object.println!("downcast_err = {:?}", downcast_err)
: This prints the result of the downcast attempt.
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...