rustUsing error with context in Rust
, how can I print the line number of an error?
Using the line!
macro, you can print the line number of an error in Rust. This macro is part of the std::macros
module. Here is an example of how to use it:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let x = 5;
let y = 0;
let z = x / y;
println!("{}", z);
Ok(())
}
This code will produce an error, and the line number of the error can be printed using the line!
macro:
thread 'main' panicked at 'attempt to divide by zero', src/main.rs:7:9
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
Here is a breakdown of the code parts:
use std::error::Error;
: This imports theError
trait from thestd::error
module.let x = 5;
: This creates a variablex
with the value5
.let y = 0;
: This creates a variabley
with the value0
.let z = x / y;
: This creates a variablez
with the value ofx
divided byy
.println!("{}", z);
: This prints the value ofz
to the console.Ok(())
: This returns anOk
result with an empty tuple.thread 'main' panicked at 'attempt to divide by zero', src/main.rs:7:9
: This is the output of theline!
macro, which prints the line number of the error (in this case, line 7).
External 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...