How to Print a Raw Pointer in Rust?

The other day I wrote an article about the dereference unary operator (*) and I needed a way to explain the unary operator by first explaining about pointers in Rust, which are the memory address location of, for example, a variable. However, I didn’t know how to print the pointer of a variable, without displaying the variable’s value.

To print a raw pointer in Rust, call the println! or print! macro and use the syntax {:p} as part of the first string format argument. Finally, pass the variable you want to see the raw pointer as the second argument of the macro println! or print! . See the following example.

let my_number = 1;
println!("my_number memory location {:p}", &my_number);

You can store in a variable the pointer of a variable by using the coearce reference &T o a variable to get the raw pointer of a given variable.

let my_number = 1;
let my_number_pointer: *const i32 = &my_number;
println!("my_number memory location {:p}", my_number_pointer);

In a similar way, you can print the raw pointer of a variable by using the mutable reference &mut T of a variable.

let mut my_number = 1;
println!("my_number memory location {:p}", &mut my_number);

// or
let mut my_number = 1;
let my_number_pointer: *const i32 = &mut my_number;

println!("my_number memory location {:p}", my_number_pointer);

There are other ways to get raw pointers such as

  • Using the into_raw function to consume a box and return the raw pointer
  • Using the macro ptrs::addr_of! or ptr::addr_of_mut!