Use of `.chunks()` and `try_for_each()`

Hi All,
I am trying the use of chunks with try_for_each for array processing, unfortunately the below code can't compile and I can't understand why and how to fix. Please help.

    let buf: &[u8; 128] = &[
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    ];

    buf.chunks(16).try_for_each( |c| {
                        let chunk_len = c.len();
                        println!("{chunk_len}");
                    });

here is the error

error[E0277]: the trait bound `(): Try` is not satisfied
  --> test.rs:24:20
   |
24 |     buf.chunks(16).try_for_each( |c| {
   |                    ^^^^^^^^^^^^ the trait `Try` is not implemented for `()`
   |
note: required by a bound in `try_for_each`
  --> /home/rust/rust/library/core/src/iter/traits/iterator.rs:2461:5

The closure you pass to try_for_each must return something that implements Try<Output=()>. The implicit () you return from your closure does not implement Try. Use for_each instead, which is the equivalent of try_for_each without a failing body. Or returning something from the closure that does implement Try<Output=()>, like Option<()> or Result<(), E>.

1 Like

Thank you for quick help!

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.