我是 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
我不知道这里发生了什么。我试图找到示例或教程来获得有关如何执行此操作的微小提示,但出于某种原因,这一定是以前没有其他人尝试过的罕见边缘事情。
最佳答案
您有两个问题:传递给 map_res
的函数(如 map 结果)必须返回一个 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));
关于types - 使用 nom 解析字面量和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090979/