3

I think ref pointer is strange in rust and if some one less newest than me can explain how it's deeply working.

fn functionc(var: &i32, opinion: &str) {
    // {:p} print the address
    println!("Ma value: address - {:p}  &   value - {:?} - {}", var, var, opinion);
}

fn main() {
    let n = 55;
    let i = 33;
    let i2 = &i;
    let i3 = &i2;
    let i4 = &i3;
    let i5 = &i4;

    functionc(&n, "normal");
    functionc(&i, "normal");

    functionc(i2, "normal");

    functionc(*i3, "normal"); // Good way
    functionc(&i3, "strange"); // Hum shouldn't work

    functionc(**i4, "normal");
    functionc(***i5, "normal");

    // functionc(****i5); Generate error: It's normal


    functionc(&&&&&&&&&&&&&&&&&&&&&&&&&&&&i3, "strange"); // Hum OK why not ;)
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1c9ff70edd88186f6e43fba957403a5f

I expected error on functionc(&i3, "strange");

But it works.

Who do magic:

let i3 = &i2;

or

functionc(&i3, "strange");

or

println!({:p});

Jonathon Reinhart
  • 116,671
  • 27
  • 221
  • 298
  • 1
    Greetings. I voted to close your question as a duplicate as a *very* similar question exists and highlights clearly the compiler's dereference algorithm. Rust isn't like C, in that the compiler will actively assist you by dereferencing as many times as needed. – Sébastien Renauld Nov 03 '19 at 15:25
  • 1
    Thx Jonathon Reinhart I have my answer. – Axel Schafers Nov 03 '19 at 15:31
  • (I forgot the link to the question: [What are rust's exact auto-dereferencing rules?](https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules)) – Sébastien Renauld Nov 03 '19 at 15:36

0 Answers0