Coercion of multiple references to one?

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

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

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

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

One guess is - 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.


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.