Skip to content

Commit

Permalink
expand dbg! example usage
Browse files Browse the repository at this point in the history
  • Loading branch information
mikemorris committed Aug 28, 2021
1 parent bd2c596 commit 255a638
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions src/ch05-02-example-structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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

Expand All @@ -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
Expand Down

0 comments on commit 255a638

Please sign in to comment.