1

I have a struct like this.

pub struct MemTableEntry {
    pub key: Vec<u8>,
    pub value: Option<Vec<u8>>,
    pub timestamp: u128,
    pub deleted: bool,
}

I wanted to calculate the size of each field of the struct programmatically. What are the ways to do that?

Aziz
  • 928
  • 1
  • 10
  • 18
  • Duplicate of [How do I get the runtime memory size of an object?](https://stackoverflow.com/questions/62613488/how-do-i-get-the-runtime-memory-size-of-an-object) – Herohtar Jan 15 '22 at 07:23
  • Each language aligns structs in memory in different ways. a **sizeof** calls returns the byte size at which it is exactly placed in memory, not the actual size of the struct. So you have to calculate it yourself for each field. – SeanTolstoyevski Jan 15 '22 at 11:31
  • Does this answer your question? [How to get the size of a struct field in Rust without instantiating it](https://stackoverflow.com/questions/61046063/how-to-get-the-size-of-a-struct-field-in-rust-without-instantiating-it) – Filipe Rodrigues Jan 15 '22 at 13:05
  • @FilipeRodrigues It does not, but link of the first comment does. – Aziz Jan 15 '22 at 13:12

1 Answers1

1

We can use the std::mem::size_of_val and pass the reference of each fields. The returned type is usize which itself can be 4 or 8 bytes based on the target machine.

let entry = MemTableEntry{
    key: b"Hello".to_vec(),
    value: Some(b"World".to_vec()),
    timestamp: 123u128,
    deleted: false
};

let size = mem::size_of_val(&entry.key)
    + mem::size_of_val(&entry.value)
    + mem::size_of_val(&entry.timestamp)
    + mem::size_of_val(&entry.deleted);

assert_eq!(65, size);

Note: Please look at the @Caesar's comment below about memory.

Aziz
  • 928
  • 1
  • 10
  • 18