Yes, there is some compiler magic that optimizes Option<ptr> for a single pointer (most of the time).
use std::mem::size_of; macro_rules! show_size { (header) => ( println!("{:<22} {:>4} {}", "Type", "T", "Option<T>"); ); ($t:ty) => ( println!("{:<22} {:4} {:4}", stringify!($t), size_of::<$t>(), size_of::<Option<$t>>()) ) } fn main() { show_size!(header); show_size!(i32); show_size!(&i32); show_size!(Box<i32>); show_size!(&[i32]); show_size!(Vec<i32>); show_size!(Result<(), Box<i32>>); }
The following sizes are printed (on a 64-bit machine, so pointers are 8 bytes):
// As of Rust 1.22.1 Type T Option<T> i32 4 8 &i32 8 8 Box<i32> 8 8 &[i32] 16 16 Vec<i32> 24 24 Result<(), Box<i32>> 8 16
Note that &i32 , Box , &[i32] , Vec<i32> all use zero-pointer optimization within Option !
huon May 13 '13 at 5:40 am 2013-05-13 05:40
source share