9951 explained code solutions for 126 technologies


rustHow to filter a vector of strings in Rust


To filter a vector of strings in Rust, you can use the filter() method. This method takes a closure as an argument, which is used to determine which elements of the vector should be kept. The closure should return a boolean value, with true indicating that the element should be kept and false indicating that it should be discarded. For example, the following code will filter a vector of strings to only include strings that are longer than 5 characters:

let strings = vec!["foo", "bar", "baz", "quux"];
let filtered_strings = strings.filter(|s| s.len() > 5);

The output of this code will be a vector containing only the strings "baz" and "quux".

For more information on the filter() method, see the Rust documentation. Additionally, the Rust by Example page provides a more detailed example of how to use the filter() method.

Edit this code on GitHub