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.
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.
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]); }SAMPLE FOR FILL: 6
Does fill()
perform faster compared to a for
-loop? Sometimes functions that act upon many elements at once are more optimized.
for
-loop to assign each element in the array to the value 5. The effect is the same as the fill function.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
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.