Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printing a pointer print the same thing as printing the dereferenced pointer?

From the Rust guide:

To dereference (get the value being referred to rather than the reference itself) y, we use the asterisk (*)

So I did it:

fn main() {     let x = 1;     let ptr_y = &x;     println!("x: {}, ptr_y: {}", x, *ptr_y); } 

This gives me the same results (x=1; y=1) even without an explicit dereference:

fn main() {     let x = 1;     let ptr_y = &x;     println!("x: {}, ptr_y: {}", x, ptr_y); } 

Why? Shouldn't ptr_y print the memory address and *ptr_y print 1? Is there some kind of auto-dereference or did I miss something?

like image 946
Vega Avatar asked Jan 09 '15 01:01

Vega


People also ask

What does* do to a pointer?

If you see the * in a declaration statement, with a type in front of the *, a pointer is being declared for the first time. AFTER that, when you see the * on the pointer name, you are dereferencing the pointer to get to the target.

How do you print a pointer in Rust?

If you just want to print raw pointer value, then printf!( "{}", ptr as usize) might work. For Debug types there's {:p} format pattern that prints their address. {:p} works for all references and raw pointers.

Can you print a pointer?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.


1 Answers

Rust usually focuses on object value (i.e. the interesting part of the contents) rather than object identity (memory addresses). The implementation of Display for &T where T implements Display defers directly to the contents. Expanding that macro manually for the String implementation of Display:

impl<'a> Display for &'a String {     fn fmt(&self, f: &mut Formatter) -> Result {         Display::fmt(&**self, f)     } } 

That is, it is just printing its contents directly.

If you care about object identity/the memory address, you can use the Pointer formatter, {:p}:

fn main() {     let x = 1;     let ptr_y = &x;     println!("x: {}, ptr_y: {}, address: {:p}", x, ptr_y, ptr_y); } 

Output:

x: 1, ptr_y: 1, address: 0x7fff4eda6a24 

playground

like image 122
huon Avatar answered Oct 22 '22 06:10

huon