Rust Book Example: Does dbg! return ownership or not?

Viewed 54

I am new to rust and am following along with the official guide and have a question about the following section in chapter 5.2:

#[derive(Debug)] struct Rectangle {
    width: u32,
    height: u32, }

fn main() {
    let scale = 2;
    let rect1 = Rectangle {
        width: dbg!(30 * scale),
        height: 50,
    };

    dbg!(&rect1); }

We can put dbg! around the expression 30 * scale and, because dbg! returns ownership of the expression’s value, the width field will get the same value as if we didn’t have the dbg! call there. We don’t want dbg! to take ownership of rect1, so we use a reference to rect1 in the next call.

The guide states that dbg! returns ownership of the width expressions value, then right after it says we dont want dbg! to take ownership of rect1 so we use a reference. Why wouldn't dbg! return ownership of rect1?

2 Answers

The point is that dbg! takes the ownership and then returns it back as a value it evaluates to. It works as something like this function:

fn dbg<T: Debug>(val: T) -> T {
    // some debug printing of `val`
    val
}

(The real implementation is a little more complex, since it uses the file-line-column information, exact evaluated expression, and works correctly with lifetimes of temporaries)

That is, the value is moved into the dbg!, but then moved again from dbg! into whatever binding you assign it to.

In the first case, therefore, the value of dbg! is assigned to the struct field, so this field will be equal to 30 * scale. The second case, on the other hand, also be written like this:

let rect1 = dbg!(rect1);

That is, you move the value out of rect1, print it, and then store it into new binding, also named rect1.

In that second case, it actually takes ownership of what is passed to it, that is, a reference to rect1, not rect1, which it then returns, before instantly discarding discarding it because you are not retrieving it (ie. you are not doing something like let ref_to_rect1 = dbg!(&rect1);).

Related