rustHow to display error in Rust
Rust provides a standard library module called std::error
which provides a trait called Error
that can be used to display errors. The Error
trait provides a Display
implementation which can be used to print errors.
Code example:
use std::error::Error;
fn main() {
let err = "Error message";
let err_obj = err.into();
println!("{}", err_obj);
}
Output
Error message
Explanation:
-
The
use std::error::Error
statement imports theError
trait from thestd::error
module. -
The
err
variable is a string literal containing the error message. -
The
err_obj
variable is created by converting theerr
string literal into anError
object using theinto()
method. -
The
println!
macro is used to print the error message contained in theerr_obj
object.
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...