What is the null pointer optimization in Rust?

The null pointer optimization basically means that if you have an enum with two variants, where one variant has no associated data, and the other variant has associated data where the bit pattern of all zeros isn’t a valid value, then the enum itself will take exactly the same amount of space as that associated value, using the all zeroes bit pattern to indicate that it’s the other variant.

In other words, this means that Option<&T> is exactly the same size as &T instead of requiring an extra word.

Leave a Comment