w3resource

Rust Array Filtering & Slicing

Rust Vectors, Arrays, and Slices: Exercise-9 with Solution

Write a Rust program that creates an array of floating-point numbers with size 10. Filter out the numbers less than 0.5 from the array and then slice it to get a sub-array containing the first 3 filtered numbers. Print the sub-array.

Sample Solution:

Rust Code:

fn main() {
    // Declare an array of floating-point numbers with size 10
    let numbers: [f64; 10] = [0.1, 0.6, 0.2, 0.7, 0.3, 0.8, 0.4, 0.9, 0.5, 1.0];

    // Filter out the numbers less than 0.5 from the array
    let filtered_numbers: Vec = numbers.iter().copied().filter(|&x| x >= 0.5).collect();

    // Slice the resulting vector to get a sub-array containing the first 3 filtered numbers
    let sub_array = &filtered_numbers[0..3];

    // Print the sub-array
    println!("Sub-Array: {:?}", sub_array);
}

Output:

Sub-Array: [0.6, 0.7, 0.8]

Explanation:

Here is a brief explanation of the above Rust code:

  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let numbers: [f64; 10] = [...];: This line declares an array named 'numbers' of type [f64; 10] (array of floating-point numbers with size 10) and initializes it with some floating-point numbers.
  • let filtered_numbers: Vec<f64> = ...: This line filters out the numbers less than 0.5 from the 'numbers' array using the "filter()" method and collects the filtered numbers into a new vector named 'filtered_numbers'.
  • let sub_array = &filtered_numbers[0..3];: This line slices the 'filtered_numbers' vector to get a sub-array containing the first 3 filtered numbers.
  • println!("Sub-Array: {:?}", sub_array);: This line prints the sub-array to the console using debug formatting. The {:?} format specifier prints the elements of the array slice.

Rust Code Editor:

Previous: Rust Array Sorting & Slicing.
Next: Rust Array Mapping & Slicing.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.