如何包装 nom tag_no_case 解析器?

How can I wrap a nom tag_no_case parser?

我想用特定的字符串值包装 tag_no_case 解析器以便能够重新使用它们:

pub fn schema_parser<???>(???) -> ??? {
    tag_no_case("schema")
}

这样使用

preceded(multispace0, schema_parser)(input)

我试过复制 tag_no_case 打字和其他一些随机方法,但对我没有任何作用。

类型声明应该如何才能像所示那样使用自定义解析器?

tag_no_case returns a impl Fn(Input) -> IResult<Input, Input, Error> 这意味着我们必须 return 类似于包装函数的东西。

为了简洁起见,让我们跳过所有泛型,只使用 &str,此时编译器会抱怨 returned 类型“不够通用”,因为它不是在整个生命周期中通用。我们可以通过将生命周期参数添加到函数签名并使用该参数来注释 return 类型来将其固定为单个生命周期。

最终完整的工作和编译示例:

// nom = "6.1.0"
use nom::{IResult, bytes::complete::tag_no_case, sequence::preceded};

fn schema_parser<'a>() -> impl Fn(&'a str) -> IResult<&'a str, &'a str> {
    tag_no_case("schema")
}

fn main() {
    let string = String::from("exampleschema");
    let mut parser = preceded(tag_no_case("example"), schema_parser());
    assert_eq!(parser(&string), Ok(("", "schema"))); // non-'static str
    assert_eq!(parser("exampleschema"), Ok(("", "schema"))); // 'static str
}