Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.