Pointers

Printing Pointers

You can print pointers with {:p} formatter and *const with {:?} formatter.

main.rs
fn main() {
    // String (in heap)
    let s1 = String::from("hello");           // String
    let s1_ref = &s1;                         // &String
    let s1_string = s1_ref as *const String;  // *const String

    println!("{:p} {:?}", s1_ref, s1_string); // 0x16d1f2588 0x16d1f2588

    // Slices (on stack)
    let s2 = "hello";                         // &str
    let s2_ref = &s2;                         // &&str
    let s2_string = s2_ref as *const &str;    // *const &str

    println!("{:p} {:?}", s2_ref, s2_string); // 0x16d1f2600 0x16d1f2600
}

Meaning behind {:?}

It means to debug-format a value.

First, the type of the value should derive Debug trait like this:

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

And then you can use :? formatter to print it or store its formatted value.

let v = Person {
    name: String::from("John"),
    age: 32,
};

let s = format!("{:?}", v);
println!("{}", s);          // Person { name: "John", age: 32 }

println!("{:?}", v);        // Person { name: "John", age: 32 }

println!("{v:?}");          // Person { name: "John", age: 32 }
  • {} surrounds formatting directives.

  • : separates the name / ordinal of the value being formatted. In this case({:?}), it's omitted.

  • ? is the formatting option that triggers the use of the std::fmt::Debug implementation of the value being formatted. (as opposed to the default Display trait)

Reference: Stack Overflow

Last updated