The method to utilize a function that produces a Result type with every item in a Rust HashSet is to use the iter()
method provided by the HashSet to get an iterator over the items in the set, and then use the map()
method of the iterator to apply the function to each item in the set. The map()
method returns an iterator over the results of applying the function to each item, which can then be collected into a new HashSet. Here's an example:
use std::collections::HashSet;
fn my_function(item: &i32) -> Result<i32, String> {
if *item > 0 {
Ok(*item * 2)
} else {
Err(String::from("Item must be positive"))
}
}
fn main() {
let set: HashSet<i32> = vec![1, 2, 3, 4].into_iter().collect();
let new_set: Result<HashSet<i32>, String> = set.iter().map(|item| my_function(item)).collect();
// `new_set` will contain `Ok(HashSet {2, 4, 6, 8})`
}
Note that the resulting type of the collect()
method is Result<HashSet<i32>, String>
because the my_function()
can potentially return an error.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-04-29 03:22:00 +0000
Seen: 10 times
Last updated: Apr 29 '23
What are the Cordapp Certificates used for in terms of signing and interacting?
How can SSL be used with CqlSessionFactoryBean in Springboot Cassandra?
How to set up Database First configuration in Entity Framework 7 for MVC 6?
How can I address the issue of Content Security Policy blocking more than I had anticipated?
How do I resolve a 502 error when attempting to call an HTTPS REST API from an HTTP REST API?
What does borrowing or moving a value from `stdout` mean?