I have the following stack- and heap-allocated variables:
let var1 = 10;
let var2 = Box::new(10);
Printing these outputs the same value, 10
:
println!("var1 ={} var2 ={}", var1, * var2);
When I check the size using mem::size_of_val()
, var1
is 4 and var2
is 8.
Isn't var2
a pointer to the heap? Why would a pointer be larger than the stack variable (var1
)?
Also, is the use of "*
" (i.e., *var2
) in the println!()
supposed to do anything different? I get 10 either way.
You didn't show your code for how you are invoking mem::size_of_val
but I guess from the results that you are doing this:
println!("var1 size = {}", mem::size_of_val(&var1)); // 4
println!("var2 size = {}", mem::size_of_val(&var2)); // 8
The size of var1
is the size of an i32
(4 bytes), while the size of var2
is the size of a Box
, which is just a pointer (it would be two pointers if it was a trait object). A pointer is always a usize
(8 bytes on a 64bit system).
If you dereference the box first, then the size will be that of the box's contents and you'll get the result you expect:
println!("var2 size = {}", mem::size_of_val(&*var2)); // 4
Also, is the use of "
*
" (i.e.,*var2
) in theprintln!()
supposed to do anything different? I get 10 either way.
The println!
macro, along with format!
and a few others, will always prepend a &
to a value to make sure that it's borrowed, not moved or copied. When the value is needed it will be automatically dereferenced as many times as is necessary. See this answer for more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With