I am trying to figure out how to get the size in bytes of an object in Rust where the size may or may not be known at compile time. I would like to be able to fetch the number of bytes at any point during the runtime of the program. Here's an example.
let mut v: Vec<SomeStruct> = Vec::new();
loop {
v.push(get_some_struct());
print_consumed_memory_of_vec(&v);
}
I would like to have a more generic way this than doing mem::size_of<SomeStruct> * v.len()
because often you have a trait or something where the size is not known at compile time.
Use std::mem::size_of_val
to get the size of a slice:
println!("The useful size of `v` is {}", size_of_val(&*v));
Note:
Vec<T>
to get a &[T]
because the size of the Vec
itself is just the size of three pointers, but you actually want the size of the slice that the data pointer refers to. This isn't a problem when you already have a &[T]
or a &dyn Trait
, or generally any &U
where U
is the thing whose size you want to know.Vec
; that is, the same thing as size_of::<T>() * v.len()
. If v
has unused capacity, that will not be reflected by size_of_val(&*v)
. There is no general method that tells you the size of an allocation; you must calculate that yourself. This also makes a difference for, for instance, Rc<T>
instead of Vec<T>
-- the Rc
stores its reference counts in the same allocation with the T
, but they will not be counted if you write size_of_val(&*rc)
.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