std-method

slice::first_chunk

Borrow the first N elements as a fixed-size array reference, or receive None if too short. The original slice may be longer than N. Expected stdout (not executed): [3, 7] true Common mistake: Confusing this with conversion of the entire slice, which requires equal lengths.

Formal Syntax & Structure

rust syntaxrust
slice.first_chunk::<N>()

Working Example

Example Snippetrust
fn main() {    let packet: &[u8] = &[3, 7, 9];    let header: &[u8; 2] = packet.first_chunk::<2>().unwrap();    println!("{header:?} {}", packet.first_chunk::<4>().is_none());}
Rust Reference