To check if a specified element is present in an array in Rust, you can use methods like contains
or a loop to iterate through the array and compare each element.
In this example,
numbers
with values 10, 20, 30, 40, 50.contains
method to check if element 30 is present in the vector.contains
method returns true if the element is found, otherwise false.fn main() {
let numbers = vec![10, 20, 30, 40, 50];
let element = 30;
let is_present = numbers.contains(&element);
println!("Element 30 is present: {}", is_present);
}
Element 30 is present: true
In this example,
fruits
with values 'apple', 'banana', 'cherry'.for
loop to iterate through the vector and compare each element with the specified element 'banana'.found
to true; otherwise, it remains false.fn main() {
let fruits = vec!["apple", "banana", "cherry"];
let element = "banana";
let mut found = false;
for fruit in fruits {
if fruit == element {
found = true;
break;
}
}
println!("Element 'banana' is present: {}", found);
}
Element 'banana' is present: true
In this tutorial, we learned How to check if Specified Element is present in the Array in Rust language with well detailed examples.