Home > Software engineering >  What do the '&&' and star '**' symbols mean in Rust?
What do the '&&' and star '**' symbols mean in Rust?

Time:10-31

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?

CodePudding user response:

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 = &c; // this is &&c
}

CodePudding user response:

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.

  • Related