Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the size of Option<f64> 16 bytes on 64bit Linux?

Tags:

rust

I tried this on 64bit Linux and it gives 16:

println!("Results: {}", mem::size_of::<Option<f64>>())

as I understand, this is because of:

pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);

What is the sense in a 64bit discriminant? For code written by hand, 256 will be enough, for generated code 2^16 would be a huge number, and I can not even imagine why need 2^32. Why would it use 64 bits for this?

Why does the compiler not optimize it for the Option case? 8 bits at the end of the structure should be enough.

like image 475
user1244932 Avatar asked Jan 29 '23 13:01

user1244932


1 Answers

f64 has a 64-bit alignment. Thus a type containing an f64 needs an alignment of at least 64 bits. The size of a type is guaranteed to be a multiple of its alignment. Since it can't fit in 64 bits, it needs to go up to the next multiple, 128 bits/16 bytes.

like image 66
CodesInChaos Avatar answered Feb 03 '23 12:02

CodesInChaos