10

I used to think this is similar to lvalue reference collapsing in C++, so &&T should be the same as &T, from perspective of syntax, but I am confused after I compiled the following code:

fn check_ref(x: &i32) -> i32 {
    println!("{}", x);
    x + 2
}

fn main() {
    for i in &[-3, 2, 39] {
        // i is &i32
        check_ref(i); // this works
        check_ref(&i); // this works
        check_ref(&&i); // this works

        assert_eq!(i, &i); // error[E0277]: can't compare `i32` with `&i32`
    }
}

Is it true that multiple references collapse, or does ref-to-ref have some other specific meaning?

Is this compiler error of assert_eq! only because of some tricks in Rust macros?

rustyhu
  • 1,912
  • 19
  • 28
  • 4
    After reading the 2 associated questions and answers, I still think the point of my question is a little different from them. My question emphasizes on the meaning of the Rust syntax "&&T" itself, and whether it is relative to similar concept in C++. In fact there is no "ref to ref" in C++, as the content of the link I put states, even the symbol "&&" in C++ is totally another thing(rvalue reference). So I think "&&" in the 2 languages only look similar, but "&" in Rust is more like pointer in C++, "&&T" is just pointer of pointer of T. This with auto-dereferencing makes the code I put work. – rustyhu Dec 05 '19 at 15:30
  • it is not a separate syntax. Rust does not have rvalue references. Anyway, you can make a chain of references and Rust will actually do it without replacing the chain with a single `&`, to be explicit. Anyway, when u pass chain of references to a function that accepts single `&`, Rust will automatically dereference a chain until there will be `&` – hazer_hazer Jun 29 '21 at 10:00

0 Answers0