To check if a vector is not empty in Rust, you can use the is_empty
method, which returns false
if the vector has elements.
In this example,
num_vec
with several elements.is_empty
method to check if num_vec
is not empty.!num_vec.is_empty()
returns true
, it means the vector is not empty.fn main() {
let num_vec = vec![10, 20, 30, 40, 50];
if !num_vec.is_empty() {
println!("Numeric vector is not empty");
} else {
println!("Numeric vector is empty");
}
}
Numeric vector is not empty
In this example,
str_vec
with several elements.is_empty
method to check if str_vec
is not empty.!str_vec.is_empty()
returns true
, it means the vector is not empty.fn main() {
let str_vec = vec!["apple", "banana", "cherry", "date"];
if !str_vec.is_empty() {
println!("String vector is not empty");
} else {
println!("String vector is empty");
}
}
String vector is not empty
In this tutorial, we learned How to check if a Vector is Not Empty in Rust language with well detailed examples.