【问题标题】:Return type of .peekable() isn't Peekable<T>.peekable() 的返回类型不是 Peekable<T>
【发布时间】:2018-01-19 15:32:42
【问题描述】:

我正在尝试使用 Rust 1.22.1 版本编译以下代码:

use std::str::Split;
use std::iter::Peekable;

// This is fine...
fn tokenize<'a>(code: &'a str) -> Split<'a, fn(char) -> bool> {
    code.split(char::is_whitespace)
}

// ...but this is not...
fn tokenize_peekable_bad<'a>(code: &'a str) -> Peekable<Split<'a, fn(char) -> bool>> {
    code.split(char::is_whitespace).peekable()
}

// ...however this is?
fn tokenize_peekable<'a>(code: &'a str) -> Peekable<Split<'a, fn(char) -> bool>> {
    tokenize(&code).peekable()
}

在我看来tokenize_peekable_badtokenize_peekable 应该具有完全相同的类型签名,但是tokenize_peekable_bad 给出了编译器错误,而tokenize_peekable 很好。

错误是

error[E0308]: mismatched types
  --> src/main.rs:11:5
   |
11 |     code.split(char::is_whitespace).peekable()
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found fn item
   |
   = note: expected type `std::iter::Peekable<std::str::Split<'a, fn(char) -> bool>>`
              found type `std::iter::Peekable<std::str::Split<'_, fn(char) -> bool {std::char::<impl char>::is_whitespace}>>`

谁能解释一下这个令人费解的结果?

【问题讨论】:

    标签: types rust


    【解决方案1】:

    您需要将函数指针从其特定的具体类型转换为非特定的函数指针类型:

    fn tokenize_peekable_ok_now<'a>(code: &'a str) -> Peekable<Split<'a, fn(char) -> bool>> {
        code.split(char::is_whitespace as fn(char) -> bool).peekable()
    }
    

    当您调用 tokenize 函数时,您的工作解决方案会自动执行此操作,因为类型系统必须执行的步骤数只有一个 (Split&lt;'a, fn(char) -&gt; bool {specific}&gt; -> Split&lt;'a, fn(char) -&gt; bool&gt;)。在tokenize_peekable_bad 中,当它检查返回类型时,它已经将Split 包裹在Peekable 内,因此它不知道将演员表流回原始位置。具体来说,它不在coercion site

    另见:

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 1970-01-01
      • 2022-06-28
      • 2015-04-30
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2021-02-04
      • 2021-07-19
      相关资源
      最近更新 更多