使用nom来解析文字和返回值

时间:2017-05-20 21:28:48

标签: types rust nom

我是Rust的新手,并且一直试图绕过这个三个小时,我想我会疯了。我想要的只是一个解析器,它接受字符串"true"并返回一个枚举Value::Const(true)。这就是我到目前为止所做的:

// parser.rs
use nom::*;

#[derive(PartialEq, Debug, Clone)]
pub enum Value {
    Const(bool),
}

fn true_value<T>(_: T) -> Value { Value::Const(true) }
fn false_value<T>(_: T) -> Value { Value::Const(false) }

named!(literal_true<&[u8]>, map_res!(tag!("true"), true_value));
named!(literal_false<&[u8]>, map_res!(tag!("false"), false_value));

但我得到的是:

error[E0308]: mismatched types
  --> src/parser.rs:25:1
   |
25 | named!(literal_true<&[u8], Result<Value, String>>, map_res!(tag!("true"), true_value));
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `parser::Value`, found enum `std::result::Result`
   |
   = note: expected type `parser::Value`
              found type `std::result::Result<_, _>`
   = note: this error originates in a macro outside of the current crate

我不知道这里发生了什么。我试图找到示例或教程来获得如何做到这一点的一个小小的提示,但出于某种原因,这必须是其他人没有尝试过的一些罕见的边缘事物。

1 个答案:

答案 0 :(得分:4)

您有两个问题:传递给map_res的函数(如地图结果中)必须返回Result,并且传递给named的函数签名必须指示输入和输出类型。如果您不想返回结果,可以使用map

#[derive(PartialEq, Debug, Clone)]
pub enum Value {
    Const(bool),
}

fn true_value<T>(_: T) -> Value { Value::Const(true) }
fn false_value<T>(_: T) -> Value { Value::Const(false) }

// input type and output type 
named!(literal_true<&[u8], Value>, map!(tag!("true"), true_value));
// input type can be omitted if it's &[u8]
named!(literal_false<Value>, map!(tag!("false"), false_value));