Skip to content

Commit 255a638

Browse files
committed
expand dbg! example usage
1 parent bd2c596 commit 255a638

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/ch05-02-example-structs.md

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,9 @@ Now that we're familiar with deriving the `Debug` trait for helpful `println!`
256256
formatting, let's take a look at a macro that builds on top of that functionality.
257257
The `dbg!` macro (available in Rust 1.32.0 and later) can accept any argument
258258
that implements the `Debug` trait, and will print helpful debugging context in
259-
the same style as `println!("{:?#}", rect1)`, plus the filename and line number.
259+
the same style as `println!("{:#?}", rect1)`, plus the filename, line number and
260+
argument name. `dbg!` takes ownership of (and returns a clone of) the argument
261+
passed to it, and so can even be used inline to wrap most references or values.
260262

261263
<span class="filename">Filename: src/main.rs</span>
262264

@@ -267,11 +269,38 @@ struct Rectangle {
267269
height: u32,
268270
}
269271

272+
fn get_width(rect: &Rectangle) -> u32 {
273+
rect.width
274+
}
275+
276+
fn get_height(rect: Rectangle) -> u32 {
277+
rect.height
278+
}
279+
270280
fn main() {
271-
let rect1 = Rectangle { width: 30, height: 50 };
281+
let rect1 = Rectangle {
282+
width: 30,
283+
height: 50,
284+
};
272285

273-
dbg!(rect1);
286+
println!("width: {}", get_width(dbg!(&rect1)));
287+
println!("height: {}", get_height(dbg!(rect1)));
288+
}
289+
```
290+
291+
Now when we run the program, we’ll see the following output:
292+
293+
```text
294+
[src/main.rs:21] &rect1 = Rectangle {
295+
width: 30,
296+
height: 50,
297+
}
298+
width: 30
299+
[src/main.rs:22] rect1 = Rectangle {
300+
width: 30,
301+
height: 50,
274302
}
303+
height: 50
275304
```
276305

277306
Rust has provided a number of traits for us to use with the `derive` annotation

0 commit comments

Comments
 (0)