【问题标题】:Cannot infer type for type parameter `I` declared on the function `tuple` when parsing with nom使用 nom 解析时,无法推断函数“元组”上声明的类型参数“I”的类型
【发布时间】:2020-11-03 15:31:34
【问题描述】:

我正在尝试使用nomtuple 函数。该文档提供了以下示例:

use nom::sequence::tuple;
use nom::character::complete::{alpha1, digit1};
let parser = tuple((alpha1, digit1, alpha1));

当我尝试它时,我得到一个编译错误:

    error[E0283]: type annotations needed
   --> src/main.rs:20:18
    |
20  |     let parser = tuple((alpha1, digit1, alpha1));
    |         ------   ^^^^^ cannot infer type for type parameter `I` declared on the function `tuple`
    |         |
    |         consider giving `parser` a type
    | 

如果我想为变量添加一个类型,它会是什么?我知道它必须是FnMut 的一些变体,但我不确定它究竟是如何工作的。

Cargo.toml

[dependencies]
nom = ">=5.0"

【问题讨论】:

  • 如果您实际上从文档中复制了完整的示例,包括assert_eq!() 调用,它编译得很好。使用解析器的行为类型推断提供了所需的额外提示。

标签: rust nom


【解决方案1】:

类型推断需要足够的信息来实际推断类型。您可以通过复制文档中的完整示例来提供所需的信息,包括两个 assert_eq!() 语句:

use nom::sequence::tuple;
use nom::character::complete::{alpha1, digit1};
let mut parser = tuple((alpha1, digit1, alpha1));

assert_eq!(parser("abc123def"), Ok(("", ("abc", "123", "def"))));
assert_eq!(parser("123def"), Err(Err::Error(("123def", ErrorKind::Alpha))));

额外的调用通知编译器tuple()返回的函数的参数和返回类型,这反过来又为编译器提供了足够的信息来推断tuple()调用的所有类型参数。

或者,您可以将类型参数显式传递给tuple() 函数。以下是 Rust 能够推断所有类型所需的最少信息:

let _parser = tuple::<&str, _, (_, _), _>((alpha1, digit1, alpha1));

请注意,类型推断如何在 Rust 中工作的细节不是语言规范的一部分,并且可能会在未来的 Rust 版本中发生变化。虽然 Rust 具有很强的向后兼容性保证,但有时您可能需要在升级到较新版本时向代码添加一些类型注释。

【讨论】:

  • 谢谢,这很有意义。
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多