Loops and Pointers - *num and num are the same

I have some code (below) and the results when running are the same but I am printing num and also *num. Does anyone understand and can say why num and *num generates the same output?

fn main() {
let v = vec![1,2,2,4,4];
for num in &v {
println!("{}", *num);
}
for num in &v {
println!("{}", num);
}
println!("{:?}", v);
}

1
2
2
4
4
1
2
2
4
4
[1, 2, 2, 4, 4]

Welcome! Please see the pinned code formatting post.

Printing via {} is performed by the Display trait, and if a type T implements Display, then all levels of references &T, &&T, &&&&&&&&&T, etc, defer to that same implementation.

In the first loop, you're dereferencing an &i32 and printing the i32. In the second loop, you're just printing the &i32, but again, the output is going to be the same as with the i32.

(Depending on how the println! macro is implemented, you might even be printing &i32 and &&i32 technically.)

Here's the implementation that shows that all layers of &&&T defer to T: Display (though it may not be obvious until you have more practice reading implementation signatures such as this one).

1 Like

If you are interested in printing the pointer, you can do so with the following

println!("{:p}", num);

Relevant documentation link

1 Like