std-method
Calculate an array layout safely
Use array layout calculation rather than unchecked multiplication. The result incorporates the element size and alignment and rejects excessive requests. A valid layout is only a description of a potential allocation. Expected stdout (not executed): size=12 overflow=true Common mistake: Calculating byte counts with arithmetic that can overflow before checking.
Formal Syntax & Structure
rust syntaxrust
Layout::array::<T>(count)Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::alloc::Layout; let layout = Layout::array::<u8>(12).unwrap(); println!("size={}", layout.size()); println!("overflow={}", Layout::array::<u8>(usize::MAX).is_err());}