Deref coercion does not work inside braces?

I just found out that deref coercion seemingly doesn't work for an expression inside braces. e.g. &foo works, and &{ foo } doesn't. Full example:

struct One;
struct Two(One);

impl std::ops::Deref for Two {
    type Target = One;
    fn deref(&self) -> &Self::Target { &self.0 }
}

fn hmm(one: &One) {}

fn main() {
    let two = Two(One);
    hmm(&two); // works
    hmm(&{ two }); // doesn't work
}

Playground link

My two questions are:

  • What's going on?

  • Is there anything I can put inside the braces to stop it from breaking? The real code uses a macro, and I'd like to fix the macro if possible:

    macro_rules! foo {
      () => {{ // <-- these are the pesky braces
        let x = bar();
        // ...
        x
      }}
    }
    
    hmm(&foo!())
    

The reference describes coercion but it's not clear from that whether or not your example is supposed to work.

As a workaround, you can force a dereference using the * operator, like &*{ two }

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.