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?
When using the
{}syntax in a format string, you are requesting that the value be formatted using its implementation of theDisplaytrait. 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'sDisplayimplementation, which is why there is no difference in the output. (Note that the same is true ofDebug.)