14

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.

1

1 Answer 1

22

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:

  • You must dereference a 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.
  • This gives you the size of the populated part of the 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).
1
  • 1
    Thanks @trentcl . Your notes were especially helpful. I wasn't dereferencing to get the slice.
    – DataDao
    Jun 27, 2020 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.