Practice: Steps happening in deref coercion

โš“ rust    ๐Ÿ“… 2025-07-04    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 3      

surdeus

I've learnt part of the topic of dereferencing. As a self-made exercise I tried to follow the steps of dereferencing going from &Box<i32> (one or nested) to &i32.

Here I simply expose my reasoning to see whether there are important corrections to be made.

The snippet is:

fn main() {
    let bbox:Box<i32> = Box::new(5);
    fn a (b:&i32){
        println!("{}",b);
    }
    a(&bbox); // we expect that &Box can coerce to &i32
}

Having read Deref coercions in the book and the reference the process is basically applying .deref() until the obtained type fits the explicit type.

It seems the procedure โ€“for this random case I used as an exerciseโ€“ would be:

  1. Start with &bbox=&Box<i32> which is an &T.
    • Any &-type must implement Deref, so we can do things like *&T.
    • &T will do the standard method search and find that &Box is accepted by deref(&self) so it stops there (otherwise it would try with &&Box, &mut &Box, Box,...)
    • It applies the first &bbox.deref() to get &T which should be something like &** if I understand correctly. (first dereferences &self and second one gets to the data T.)
  2. Had we nested boxes to the i32 this would be (&**(&**)) repeatedly.
  3. We now have&T=&i32.
  4. That could still keep de-referencing, but since it matches the type annotation / signature, it stops.

6 posts - 3 participants

Read full topic

๐Ÿท๏ธ rust_feed