Coercion of multiple references to one?

Hi all, I'm curious of why this code works.

fn test<'a>(input: &'a str) -> &'a str {
    &&&&input
}

fn main() {
    let input = String::from("hello");
    test(&input);
}

I think there must be coercion happend that makes &&&&&str converted to &str, but I cannot find any document saying that.

One guess is deref.rs - source

This follows from the list of coercion types in the Rust Reference. Two are applicable here:

  • T_1 to T_3 where T_1 coerces to T_2 and T_2 coerces to T_3 (transitive case)
  • &T or &mut T to &U if T implements Deref<Target = U>.

First, since &T: Deref<Target = T>, &&&&&str can be coerced to &&&&str, &&&&str to &&&str, &&&str to &&str, and &&str to &str. Then, by the transitive case, &&&&&str can be coerced to &str, matching your observation.

3 Likes