Allow iterator to not be used


I have the following trait implementation:

    type Result = Box<dyn Iterator<Item = V> + 'a>;

    fn traverse(self) -> Self::Result {
            ...the iterator...

The traverse function has side effect and returns an iterator. It is possible that the user don't care about the iterator and only want the side effects to be applied.

Every time I use the function without using the iterator I get the following warning

unused boxed `Iterator` trait object that must be used

I could write use the let _ = trick but it's very annoying.
I tried to use the #[allow(unused_must_use)] on the function but it doesn't seem to change anything. Of course when I use it in the module it works. But I don't want to write in every file using the function.

Is there a way of doing it?

You can wrap the boxed iterator in a custom type that is not #[must_use]:

struct BoxedIter<'a, V>(Box<dyn Iterator<Item = V> + 'a>);

impl<V> Iterator for BoxedIter<'_, V> {
    type Item = V;
    fn next(&mut self) -> Option<V> { }
    // You might also want to implement `size_hint`, `fold`, `try_fold`.

// ...
   type Result = BoxedIter<'a, V>;

Maybe it would be better to have a separate method for the side effect alone?


I like that idea, and the separate method could be implemented as simply as:

fn do_traverse(self) {
    let _ = self.traverse();
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.