What do the '&&' and star '**' symbols mean in Rust?

167 Views Asked by At
fn main() {
    let c: i32 = 5;
    let rrc = &&c;
    println!("{}", rrc); // 5
    println!("{}", *rrc); // 5
    println!("{}", **rrc); // 5
}

In C/C++ language, rrc likes a two level pointer. In this example, rrc doesn't mean this in rust. What do & and * mean in Rust?

2

There are 2 best solutions below

0
jthulhu On BEST ANSWER

The reason they all print the same thing is that borrows (&T) in Rust implements Display for T: Display by dispatching it to the pointed type. If you want to print the actual pointer value, you have to use {:p}.

let c = 5;
let rrc = &&c;
println!("{:p}", rrc); // 0x7ffc4e4c7590
println!("{:p}", *rrc); // 0x7ffc4e4c7584
println!("{}", **rrc); // 5

See the playground.

0
LeoDog896 On

It is simply two reference operators. The reason why they all print 5 is because when printing a reference it automatically de-references it:

fn main() {
  let c: i32 = 5;
  let rrc = &c;
  let rrc = &rrc; // this is &&c
}