【问题标题】:How to convert &[u8] to impl Iterator<Item = u8>? [duplicate]如何将 &[u8] 转换为 impl Iterator<Item = u8>? [复制]
【发布时间】:2021-05-14 12:15:03
【问题描述】:

我想将&amp;[u8] 传递给一个接受u8 迭代器的函数:

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

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

Playground

以上行不通。它错误:

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`

这是因为迭代器被实现为传递引用,而不是值。有没有办法在不更改g 签名的情况下完成这项工作?

【问题讨论】:

    标签: rust iterator slice


    【解决方案1】:

    您需要数据的自有版本,u8,而不是迭代器返回的 &amp;u8

    在迭代器上使用cloned

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

    Playground

    【讨论】:

    • 请在回答之前搜索重复的问题。知道答案后,您就有了一种独特的能力,可以找到提问者没有的重复项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2021-05-26
    • 2015-09-26
    • 1970-01-01
    相关资源
    最近更新 更多