From 255a6385af689d4a7744a5698007d701d42929c2 Mon Sep 17 00:00:00 2001 From: Mike Morris Date: Sat, 28 Aug 2021 08:51:24 -0400 Subject: [PATCH] expand dbg! example usage --- src/ch05-02-example-structs.md | 35 +++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/src/ch05-02-example-structs.md b/src/ch05-02-example-structs.md index 16da3a038c..a7fb79fa12 100644 --- a/src/ch05-02-example-structs.md +++ b/src/ch05-02-example-structs.md @@ -256,7 +256,9 @@ Now that we're familiar with deriving the `Debug` trait for helpful `println!` formatting, let's take a look at a macro that builds on top of that functionality. The `dbg!` macro (available in Rust 1.32.0 and later) can accept any argument that implements the `Debug` trait, and will print helpful debugging context in -the same style as `println!("{:?#}", rect1)`, plus the filename and line number. +the same style as `println!("{:#?}", rect1)`, plus the filename, line number and +argument name. `dbg!` takes ownership of (and returns a clone of) the argument +passed to it, and so can even be used inline to wrap most references or values. Filename: src/main.rs @@ -267,11 +269,38 @@ struct Rectangle { height: u32, } +fn get_width(rect: &Rectangle) -> u32 { + rect.width +} + +fn get_height(rect: Rectangle) -> u32 { + rect.height +} + fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; + let rect1 = Rectangle { + width: 30, + height: 50, + }; - dbg!(rect1); + println!("width: {}", get_width(dbg!(&rect1))); + println!("height: {}", get_height(dbg!(rect1))); +} +``` + +Now when we run the program, we’ll see the following output: + +```text +[src/main.rs:21] &rect1 = Rectangle { + width: 30, + height: 50, +} +width: 30 +[src/main.rs:22] rect1 = Rectangle { + width: 30, + height: 50, } +height: 50 ``` Rust has provided a number of traits for us to use with the `derive` annotation