Skip to content

Smart Pointer dereferencing rules #538

@joliss

Description

@joliss

I'm reading the Smart Pointers chapter, and I found myself feeling confused about two things for quite a while:

  1. I was first left wondering why we can use a Box without dereferencing it in the Box chapter in println!("b = {}", b);. Then I thought that the automatic (de)referencing rules ("Where's the -> operator?", Chapter 5) might apply. Then I tried passing a Box<i64> into an i64 -> () function, which failed, so I finally concluded that we do need explicit dereferencing (*b), except that Box implements the Display trait so we can pass it directly into println!.

    So the problem I'm reporting here is that I ended up with the wrong intuition upon reading the examples. Perhaps being more explicit about what's going might help.

    Also, I wonder if it might be a good idea to link to the automatic (de)referencing rules somewhere in the Smart Pointers chapter as a reminder, because surely they are relevant here.

  2. The deref coercion rules at the bottom of the Deref chapter say:

    Rust does deref coercion when it finds types and trait implementations in three cases:

    • From &T to &U when T: Deref<Target=U>.
    • ...

    I was unclear how this rule would deref *my_favorite_song from Mp3 into a Vec, because my_favorite_song is of type Mp3 (T) and not &Mp3 (&T) -- literally until I wrote this issue, and then I realized that Rust probably automatically inserts an & to make it work, per the same automatic (de)referencing rule as above. This might be worth pointing out explicitly, if that's what's actually hapenning.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions