How to check if an element is contained in a vector in Rust?
Hi! I'm new to Rust and trying to figure out vectors. I have a `Vec`, and I need to check if a certain number is in it. In other languages (like JavaScript or Python), I would just write `if (array.includes(5))` or `if 5 in list:`, but in Rust I can't find anything similar.
Here's my code:
```rust
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
if numbers.contains(5) {
println!("Found it!");
}
}
```
But the compiler gives an error: "no method named `contains` found for struct `Vec` in the current scope". I tried looking in the documentation, but there are so many methods that I got confused. Maybe I'm doing something wrong? How do I properly check if an element is in a vector? And do I need to import something? I'd appreciate examples with explanations!
No answers yet.
Log in to leave an answer
Blogs
Functional Programming in JavaScript: Basics and Examples