Displaying references

50 Views Asked by At

I have this code here.

fn main() {
    // Assign a reference of type `i32`. The `&` signifies there
    // is a reference being assigned.
    let reference = &4;

    match reference {
        val => println!("Got a value via destructuring: {}", val),
    }
    match *reference {
        val => println!("Got a value via destructuring: {}", val),
    }
}

I was expecting to get a result like:

Got a value via destructuring: &4
Got a value via destructuring: 4

But I got

Got a value via destructuring: 4
Got a value via destructuring: 4

Could someone explain what is going on here?

1

There are 1 best solutions below

0
cdhowie On

When using the {} syntax in a format string, you are requesting that the value be formatted using its implementation of the Display trait. There is a built-in implementation for the primitive numeric types, which explains the case where you are formatting a number.

But what about a reference to a number? Well, there is a built in blanket implementation for all references to types that implement Display: impl<T> Display for &T where T: Display. This implementation simply delegates to the referent's Display implementation, which is why there is no difference in the output. (Note that the same is true of Debug.)