Transform Fixed Arrays With array::map
Apply array::map to fixed-size buffers: the result keeps the same length at compile time, can change element type, and never touches the heap.
Code
fn main() {
// a fixed-size sampling frame: raw readings for 4 channels
let raw: [u16; 4] = [1000, 1023, 988, 1010];
// array::map returns a new array: length fixed at compile time, element type free to change, and no heap involved
let calibrated: [f64; 4] = raw.map(|sample| sample as f64 / 1023.0);
println!("calibrated: {calibrated:?}");
// each channel gets a limit check: the array transforms wholesale into a boolean array
let flagged: [bool; 4] = raw.map(|s| s > 1020);
println!("flagged: {flagged:?}");
// a Vec would need iter plus collect, and it would allocate on the heap
let raw_vec: Vec<u16> = raw.to_vec();
let scaled: Vec<u16> = raw_vec.iter().map(|s| s * 2).collect();
println!("scaled: {scaled:?}");
// map cannot add or drop elements: the result length always equals the input
let doubled: [u16; 4] = raw.map(|s| s.saturating_mul(2));
println!("doubled: {doubled:?}");
}Inside the snippet
Transform Fixed Arrays With array::map comes down to the function main.
Using it
Signature: fn main()
Running the file prints labeled results such as calibrated:, flagged:, scaled: — each operation’s effect is visible in the output.
Key statements
let scaled: Vec<u16> = raw_vec.iter().map(|s| s * 2).collect();
let calibrated: [f64; 4] = raw.map(|sample| sample as f64 / 1023.0);
let doubled: [u16; 4] = raw.map(|s| s.saturating_mul(2));
Interactive Tools for This Topic
FAQ
- What does Transform Fixed Arrays With array::map print when run?
- Execute the whole file; each printed line is prefixed with a label like `calibrated:`, `flagged:`, `scaled:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.