Hi,
I am new to Rust. Is there a way of printing out the Structure and content of variables in the commandline similar to var_dump and print_r in PHP. It would help me a lot to understand some structs or vectors.
Hi,
I am new to Rust. Is there a way of printing out the Structure and content of variables in the commandline similar to var_dump and print_r in PHP. It would help me a lot to understand some structs or vectors.
I guess this will help you
Ps. read the whole book (starting with chapter 1 (!)), if you want to learn the rust language.
use std::fmt::Debug;
#[derive(Debug)] <- it's important
struct Point {
x: i32,
y: i32
}
fn main() {
let p = Point {x:1, y:2};
println!("{:?}", p);
} ^
|_____ this important too
And if the compiler swears in the case of a more complex data structure - see the recommendation above.
Thanks a lot. This will help a lot.
Surprisingly I did not even have to use this at all. :? or :#? did already the job. And shame on me the compiler suggest tu use that because Display was not implemented by the crate
use std::fmt::Debug;
#[derive(Debug)] <- it's important
FYI, use std::fmt::Debug
is not needed if you're deriving Debug
- you only need to pull it in if you're going to implement it manually.
You also may be interested in the new-ish dbg!
macro, which can be wrapped around any expression in order to print some helpful info - for example:
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 2, y: 1 };
// dbg! returns whatever you pass in, so you can pretty much use
// it anywhere you'd write an expression - for example, right in the
// middle of an if condition!
if dbg!(p1) == dbg!(p2) {
// Some code here...
}
}
This would print:
[src/main.rs:11] p1 = Point {
x: 1,
y: 2,
}
[src/main.rs:11] p2 = Point {
x: 2,
y: 1,
}
Note that you get the filename, the line number, and the original expression in your output, as well as the actual value!
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.