When you have an Option<&T>
, the compiler knows that NULL
is never a possible value for &T
, and encodes the None
variant as NULL
instead. This allows for space-saving:
use std::mem;
fn main() {
assert_eq!(mem::size_of::<&u8>(), mem::size_of::<Option<&u8>>());
}
However, if you do the same with a non-pointer type, there's no extra bits to store that value in and extra space is required:
use std::mem;
fn main() {
// fails because left is 1 and right is 2
assert_eq!(mem::size_of::<u8>(), mem::size_of::<Option<u8>>());
}
In general, this is correct. However, I'd like to opt-in to the optimization because I know that my type has certain impossible values. As a made-up-example, I might have a player character that has an age. The age may be unknown, but will never be as high as 255
:
struct Age(u8);
struct Player {
age: Option<Age>,
}
I'd like to be able to inform the optimizer of this constraint - Age
can never be 255
, so it's safe to use that bit pattern as None
. Is this possible?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…