rustHow to get error as string in Rust
In Rust, you can get the error as a string using the to_string()
method. This method is available on the std::error::Error
trait, which is implemented by all types that implement the std::error::Error
trait.
Code example:
use std::error::Error;
fn main() {
let err: Box<dyn Error> = Box::new(std::io::Error::new(std::io::ErrorKind::Other, "oh no!"));
let err_string = err.to_string();
println!("Error as string: {}", err_string);
}
Output
Error as string: Other: oh no!
Explanation of code parts:
use std::error::Error;
: This imports theError
trait from thestd::error
module.let err: Box<dyn Error> = Box::new(std::io::Error::new(std::io::ErrorKind::Other, "oh no!"));
: This creates aBox
containing anError
instance with theErrorKind
ofOther
and the message"oh no!"
.let err_string = err.to_string();
: This calls theto_string()
method on theError
instance, which returns the error as a string.println!("Error as string: {}", err_string);
: This prints the error string to the console.
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...