How can i iterate over two different iterators?

Hello everyone,

i am trying to iterate over two different types of iterators, but i couldn't find a way to do it

    async fn _from_file(&self, file: &String) -> Result<()> {
        let file = File::open(file)?;
        let reader = BufReader::new(file);

        self._run(reader.lines()).await
    }

    async fn _from_set(&self, set: HashSet<Result<String>>) -> Result<()> {
        self._run(set.iter()).await
    }

    async fn _run<I: Iterator<Item = Result<String>>>(&self, iter: I) -> Result<()> {
        let futs = FuturesUnordered::new();

        for path in iter {
            println!("{:?}", path);
        }

        Ok(())
    }

the Result type is defined in lib.rs like this

pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

The error i am getting

49 |         self._run(reader.lines()).await
   |              ^^^^ expected struct `std::io::Error`, found struct `std::boxed::Box`
53 |         self._run(set.iter()).await
   |              ^^^^ expected reference, found enum `std::result::Result`

In both cases the problem is that the item type of the iterator does not match.

In the first case, reader.lines() produces the wrong error type.

_run:           Result<String, Box<dyn Error>>
reader.lines(): Result<String, std::io::Error>

You can fix this by combining Iterator::map with Result::map_err.

self._run(reader.lines().map(|item| item.map_err(|err| Box::new(err))))

Similarly, in the second case, the issue is that the item type is incorrect. The iter() method only borrows from the HashSet, so it can only produce references into the HashSet, and not owned values.

_run:        Result<String, Box<dyn Error>>
set.iter(): &Result<String, Box<dyn Error>>

To fix this you can either clone each item, or take ownership of the items by destroying the HashSet with into_iter().

// take ownership
self._run(set.into_iter()).await
// or clone
self._run(set.iter().cloned()).await
2 Likes

Cloned won't work here because Box<dyn Error> doesn't implement clone

1 Like

Fair point.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.