Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created October 20, 2025 11:46
Show Gist options
  • Select an option

  • Save rust-play/2cf0df267cb59f5c488285a7cc16fcd6 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/2cf0df267cb59f5c488285a7cc16fcd6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// Niche optimization
// A clever way to make Option<T> (or similar enums) use the exact same memory
// size as T itself, without wasting space for a "tag"
// (like a boolean for Some/None).
use std::mem::{size_of, MaybeUninit};
fn main() {
// Seeing the size overhead of using Option types
println!("size_of::<i32>(): {}", size_of::<i32>());
println!(
"size_of::<Option<i32>>(): {}",
size_of::<Option<i32>>() /* `i32` can be a zero value (0)
therefore Niche optimization cannot work here. Instead
`None` will be given another byte size. */
);
// The size of a pointer (& and &mut) is usize.
println!("---\nsize_of::<&i32>(): {}", size_of::<&i32>());
println!(
"size_of::<Option<&i32>>(): {}",
size_of::<Option<&i32>>() /* Niche optimization. Why does it
work here and not in `Option<i32>` because a pointer (& or &mut)
cannot be null or zero. */
);
println!("size_of::<usize>(): {}", size_of::<usize>());
println!("---");
// No overhead with MaybeUnint types; as types are uninitialized
println!("size_of::<i32>(): {}", size_of::<i32>());
println!(
"size_of::<MaybeUninit<i32>>(): {}", size_of::<MaybeUninit<i32>>()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment