243. slice::as_flattened — Treat a Slice of Arrays as One Flat Slice, No Copy
You’ve got a Vec<[f32; 3]> of RGB pixels and an API that wants &[f32]. The manual flatten allocates a whole second buffer. as_flattened hands you the same bytes as a flat &[f32] — zero copies, zero allocation.
The copy you didn’t need
A slice of fixed-size arrays is already contiguous in memory. But reach for a flat view the obvious way and you rebuild it element by element into a fresh Vec:
| |
That collect walks all six values and heap-allocates a second buffer — pure waste when the layout you want is already sitting there.
as_flattened is a free reinterpretation
| |
<[[T; N]]>::as_flattened takes &[[T; N]] and returns &[T] covering the exact same memory. No copy, no allocation — just a pointer and a length. The result borrows the original, so it stays as cheap as it looks.
Mutate through the flat view
as_flattened_mut gives you &mut [T], so you can run a flat transform over structured data without unpacking it:
| |
Same storage, edited in place — the array grouping is still there when you’re done.
Where it shines: handing structured data to flat APIs
Vertex buffers, audio frames, matrices — anything you model as [T; N] but a lower-level API wants as one long run:
| |
You keep the readable [[f64; 3]; 2] shape in your own code and pass a &[f64] across the boundary — no glue buffer in between. Whenever you catch yourself flatten().collect()-ing a slice of arrays just to change its type, as_flattened is the zero-cost version.