Array fill ExampleUse the fill function to populate all the elements in an array with a specific value, without a for-loop.
This page was last reviewed on Jan 25, 2024.
Fill. Often in programs we want to set each value in an array to a specific number. A for-loop could iterate over each element and assign it.
But with fill, we can avoid the for-loop and keep out code cleaner and simpler. This may help reduce bugs. And fill() is easier to read again when we forget about the logic.
Fill example. To begin, we specify an array of arrays—this is like a 2D array. There are 200 arrays, and each nested array has 200 elements. We then fill each nested array.
Tip For a 1D array, we would not need a for-loop at all. But this program has 200 separate arrays.
use std::time::*; fn main() { // 200 by 200 array. let mut data = [[0; 200]; 200]; // Fill each array in the 2D array with a value. for i in 0..data.len() { data[i].fill(6); } // Test that the array was filled. println!("SAMPLE FOR FILL: {}", data[100][100]); }
Benchmark. Does fill() perform faster compared to a for-loop? Sometimes functions that act upon many elements at once are more optimized.
Vec Equals
Version 1 This version of the code calls the fill function repeatedly on the array. It fills it with the value 5.
Version 2 Here we use a for-loop to assign each element in the array to the value 5. The effect is the same as the fill function.
Result The fill() function is the same speed. The two functions were likely optimized to the same code.
use std::time::*; fn main() { // Data to fill. let mut array = [0; 15]; if let Ok(max) = "10000".parse::<usize>() { // Version 1: use fill. let t0 = Instant::now(); let mut sum = 0; for _ in 0..max { for i in 0..max { array.fill(5); } } println!("{} ms", t0.elapsed().as_millis()); // Version 2: use for-loop. let t1 = Instant::now(); for _ in 0..max { for i in 0..max { for q in 0..array.len() { array[q] = 5; } } } println!("{} ms", t1.elapsed().as_millis()); println!("{}", array[0]); } }
783 ms fill() 781 ms 5
Summary. The standard library in Rust provides many functions like fill() that can simplify programs. They reduce the size of the source text, which sometimes makes programs easier to maintain.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 25, 2024 (edit).
© 2007-2024 Sam Allen.