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::Errorstatement imports theErrortrait from thestd::errormodule. -
The
errvariable is a string literal containing the error message. -
The
err_objvariable is created by converting theerrstring literal into anErrorobject using theinto()method. -
The
println!macro is used to print the error message contained in theerr_objobject.
Helpful links:
More of Rust
- Regex example to match multiline string in Rust?
- How to map a Rust slice?
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to create a HashMap of structs in Rust?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- How to perform matrix operations in Rust?
- How to use regex lookbehind in Rust?
See more codes...