MaybeUninit Initializes Arrays Manually
Build large stack arrays with MaybeUninit::uninit, write elements in place, then assume_init once every slot is provably written.
Code
use std::mem::MaybeUninit;
fn main() {
const SIZE: usize = 64;
// uninit 数组:分配但不构造元素,避免逐个 Default 的开销
let mut buffer: [MaybeUninit<u32>; SIZE] = unsafe { MaybeUninit::uninit().assume_init() };
// 逐位写入:先写满再转换
for (i, slot) in buffer.iter_mut().enumerate() {
slot.write((i * i) as u32);
}
// 全部槽位已写:map 逐槽 assume_init 把 [MaybeUninit<u32>; N] 转成 [u32; N]
let squares: [u32; SIZE] = unsafe { buffer.map(|m| m.assume_init()) };
println!("first four: {:?}", &squares[..4]);
// 对照零初始化:MaybeUninit::zeroed 直接给全零数组,适用于不需要构造的类型
let zeros: [u32; 8] = unsafe { MaybeUninit::zeroed().assume_init() };
println!("zeroed: {zeros:?}");
// 未写满就 assume_init 是未定义行为:这是 unsafe 契约的底线
let mut partial: [MaybeUninit<u8>; 4] = unsafe { MaybeUninit::uninit().assume_init() };
partial[0].write(9);
// unsafe { partial.map(|m| m.assume_init()) }; // UB: 3 个槽位未写
println!("partial slots written: 1 of 4 (assume_init would be UB)");
}What the code does
MaybeUninit Initializes Arrays Manually is built around the function main.
One loop does the cycling here: for (i, slot) in buffer.iter_mut().enumerate().
What to watch for
- No install step: the snippet lives entirely inside the standard library.
Using it
The main signature, verbatim, is fn main()
Output lines are prefixed (first four:, zeroed:), making the effect of each step easy to see.
The key statements that remain
let squares: [u32; SIZE] = unsafe { buffer.map(|m| m.assume_init()) };
let mut buffer: [MaybeUninit<u32>; SIZE] = unsafe { MaybeUninit::uninit().assume_init() };
let mut partial: [MaybeUninit<u8>; 4] = unsafe { MaybeUninit::uninit().assume_init() };
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does MaybeUninit Initializes Arrays Manually print when run?
- No setup needed: run the file and look for labeled lines like `first four:`, `zeroed:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.