rustHow to filter a vector in Rust
To filter a vector in Rust, you can use the filter()
method. This method takes a closure as an argument and returns a new vector with only the elements that satisfy the closure's condition. For example, to filter a vector of numbers and keep only the even numbers:
let numbers = vec![1, 2, 3, 4, 5];
let even_numbers: Vec<i32> = numbers.into_iter().filter(|x| x % 2 == 0).collect();
// even_numbers is now [2, 4]
The filter()
method iterates over the vector and applies the closure to each element. If the closure returns true
, the element is kept in the new vector, otherwise it is discarded. In the example above, the closure checks if the number is even and returns true
if it is.
Helpful links
More of Rust
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to use regex to match a double quote in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace all matches using Rust regex?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
See more codes...