Search code examples
rust

Debug derive macro adds extra "&" to last field


I was looking at the output from #[derive(Debug)] for a simple case using cargo expand, where this:

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

emitted (the comments added are mine):

#[automatically_derived]
impl ::core::fmt::Debug for Point {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(
            f,
            "Point",
            "x",
            &self.x,   // <== &
            "y",
            &&self.y,  // <== &&
        )
    }
}

Note that it's &self.x but &&self.y. Tried with a few other situations and the last field always seems to get an extra &. The value looks like it takes a &dyn Debug, so I'm guessing this just gets auto-dereferenced (somewhere) and doesn't matter?

Why the extra &?


Solution

  • According to the source code:

    Unsized types need an extra indirection, but only the last field may be unsized.