Practice: Steps happening in deref coercion
โ Rust ๐ 2025-07-04 ๐ค surdeus ๐๏ธ 19I'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:
- Start with
&bbox=&Box<i32>which is an&T.- Any
&-typemust implementDeref, so we can do things like*&T. &Twill do the standard method search and find that&Boxis accepted byderef(&self)so it stops there (otherwise it would try with&&Box, &mut &Box, Box,...)- It applies the first
&bbox.deref()to get&Twhich should be something like&**if I understand correctly. (first dereferences&selfand second one gets to the dataT.)
- Any
- Had we nested boxes to the
i32this would be(&**(&**))repeatedly. - We now have
&T=&i32. - That could still keep de-referencing, but since it matches the type annotation / signature, it stops.
6 posts - 3 participants
๐ท๏ธ rust_feed