How to print the size of raw pointer?

870 views Asked by At
fn main() {
    println!("{:p}", std::mem::size_of::<*const u32>());
}

When I tried this in the playground it failed:

error[E0277]: the trait bound `usize: Pointer` is not satisfied
 --> src/main.rs:2:22
  |
2 |     println!("{:p}", std::mem::size_of::<*const u32>());
  |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Pointer` is not implemented for `usize`
  |
  = note: required by `std::fmt::Pointer::fmt`
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

Is there a way to print the size of raw pointer like *const u32?

1

There are 1 answers

0
phimuemue On
println!("{}", std::mem::size_of::<*const u32>());

{:p} requires the result of the to-be-printed-thing to satisfy Pointer, but size_of returns usize which does not satisfy Pointer. You can print a usize simply with {}.

{:p} is essentially used to print a memory location, which is not something that size_of returns.