0

I'm trying to understand why println! has the same output when printing a reference of reference. Like the example below:

fn main() {
    let value = 42;
    let reference: &i32 = &value;
    let reference2: &&i32 = &&value;
    let reference3: &&&i32 = &reference2;
    
    println!("     Value: {}", value);      // output: 42
    println!(" Reference: {}", reference);  // output: 42
    println!("Reference2: {}", reference2); // output: 42
    println!("Reference3: {}", reference3); // output: 42
}

As pointed out in this question Why does printing a pointer print the same thing as printing the dereferenced pointer?: The implementation of Display for &T where T implements Display defers directly to the contents.

So, my question is, does the display implementation recursively deference a reference until reaches the value? And why println("{}", &&value) does not print the address of value?

Ruan_fer
  • 43
  • 1
  • 6
  • 6
    I'm not sure I could write an answer that doesn't just restate what is already linked. The `Display` implementation for references will display what it references. A reference-to-reference isn't anything special. So displaying a `&&&T` will therefore display like a `&&T`, which in turn will display like a `&T`, which will display like a `T`. You can think of it as recursively dereferencing. And if you did want an address, you should use `"{:p}"` (also answered in the link). – kmdreko Jun 01 '23 at 21:53
  • @kmdreko My understanding when I read about Display and why it prints the reference value, is that I thought the deference was resolved only once, and I expected that, if the deference would still result in a reference, then would print the address. Well, was just my misunderstood. If you don´t mind, can you answer just one more question? So when Display deferences a reference, it is more like traversing a linked list than a recursion? – Ruan_fer Jun 02 '23 at 03:38
  • If you have a multi-level reference, then each level would have to be resolved to get to the next level until you get to the final value, so sure you can think of it like a linked list. I wouldn't really consider the `Display` implementation as recursion since its technically a different type being implemented separately for each dereference, but it just depends how you want to think about it. – kmdreko Jun 02 '23 at 04:19
  • 1
    Either this or the question you linked should be sufficient to answer your question, not sure what else to add either. [What are Rust's exact auto-dereferencing rules?](https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules) – cafce25 Jun 02 '23 at 05:33
  • @cafce25 This is not a duplicate of "What are Rust's exact auto-dereferencing rules?" because this is not about language auto-deref, this is about blanket implementation `impl Display for &T`. – Chayim Friedman Jun 02 '23 at 08:23

0 Answers0