Ask Your Question
1

What is the method to utilize a function that produces a Result type with every item in a Rust HashSet?

asked 2023-04-29 03:22:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-29 03:46:01 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-04-29 03:22:00 +0000

Seen: 10 times

Last updated: Apr 29 '23