w3resource

Rust Vector Searching Guide

Rust Vectors: Exercise-9 with Solution

Write a Rust program to create a vector with integers 1 to 10. Search for the number 8 in the vector and print whether it exists or not.

Sample Solution:

Rust Code:

// Define the main function
fn main() {
    // Create a vector with integers 1 to 10
    let numbers: Vec = (1..=10).collect(); // Use the collect() method to create a vector from a range

    // Search for the number 8 in the vector
    let exists = numbers.contains(&8); // Check if the vector contains the number 8

    // Print whether the number 8 exists in the vector or not
    if exists {
        println!("The number 8 exists in the vector.");
    } else {
        println!("The number 8 does not exist in the vector.");
    }
}

Output:

The number 8 exists in the vector.

Explanation:

Here is a brief explanation of the above Rust code:

  • Define the main function: fn main() { starts the definition of the main function, which is the entry point of the Rust program.
  • Create a vector with integers 1 to 10: The line let numbers: Vec<i32> = (1..=10).collect(); creates a vector numbers containing integers from 1 to 10 using the collect() method with a range (1..=10).
  • Search for the number 8 in the vector: The line let exists = numbers.contains(&8); checks whether the vector 'numbers' contains the number 8. The "contains()" method returns a boolean value indicating whether the specified element is present in the vector.
  • Print whether the number 8 exists in the vector or not: Depending on the value of the 'exists' variable, the program prints whether the number 8 exists in the vector or not using a conditional 'if' statement and the "println!" macro. If 'exists' is 'true', it prints "The number 8 exists in the vector."; otherwise, it prints "The number 8 does not exist in the vector.".

Rust Code Editor:

Previous: Rust Vector Concatenation Guide.
Next: Rust Vector Slicing Guide.

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.