1

I want to pass &[u8] into a function that takes a u8 iterator:

fn f(words: &[u8]) {
    g(words.iter())
}

fn g(words: impl Iterator<Item = u8>) {
    //
}

Playground

The above doesn't work. It errors with:

error[E0271]: type mismatch resolving `<std::slice::Iter<'_, u8> as Iterator>::Item == u8`
 --> src/lib.rs:3:5
  |
3 |     g(words.iter())
  |     ^ expected `u8`, found reference
...
6 | fn g(words: impl Iterator<Item = u8>) {
  |                           --------- required by this bound in `g`
  |
  = note:   expected type `u8`
          found reference `&u8`

This is because the iterator is implemented as passing a reference, not the value. Is there a way to make this work without changing the signature of g?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
puritii
  • 1,069
  • 1
  • 7
  • 18

1 Answers1

0

You need an owned version of the data, u8 instead of the &u8 returned by the iterator.

Use cloned on the iterator:

fn f(words: &[u8]) {
    g(words.iter().cloned())
}

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 2
    Please search for duplicate questions before answering. Knowing an answer gives you a unique ability to find the duplicates that the question asker doesn't have. – Shepmaster Feb 10 '21 at 19:02