将枚举变量用作函数的奇怪语法是什么? [英] What is this strange syntax where an enum variant is used as a function?

查看:50
本文介绍了将枚举变量用作函数的奇怪语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 示例示例代码>syn::parse.

Below is the example given by the mod documentation of syn::parse.

enum Item {
    Struct(ItemStruct),
    Enum(ItemEnum),
}

struct ItemStruct {
    struct_token: Token![struct],
    ident: Ident,
    brace_token: token::Brace,
    fields: Punctuated<Field, Token![,]>,
}

impl Parse for Item {
    fn parse(input: ParseStream) -> Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(Token![struct]) {
            input.parse().map(Item::Struct)    // <-- here
        } else if lookahead.peek(Token![enum]) {
            input.parse().map(Item::Enum)      // <-- and here
        } else {
            Err(lookahead.error())
        }
    }
}

input.parse().map(Item::Struct) 是一个有效的普通 Rust 语法(看起来不像 Item::Struct 不是一个函数),或者它是 proc_macro 库的一种特殊语法?如果是后者,是否有proc_macro 特定语法规则的文档?

Is input.parse().map(Item::Struct) a valid normal Rust syntax (appears not as Item::Struct is not a function), or is it a kind of special syntax for proc_macro libs? If the latter is the case, is there a documentation of the proc_macro specific syntax rules?

推荐答案

此语法是标准的 Rust 语法.您可以使用元组结构或类似元组结构的枚举变体作为函数.请看这个小例子:

This syntax is standard Rust syntax. You can use tuple struct or tuple struct-like enum variants as functions. See this small example:

enum Color {
    Str(String),
    Rgb(u8, u8, u8),
}

struct Foo(bool);

// Use as function pointers (type annotations not necessary)
let f: fn(String) -> Color = Color::Str;
let g: fn(u8, u8, u8) -> Color = Color::Rgb;
let h: fn(bool) -> Foo = Foo;

在下一个示例中,这些函数被直接传递给另一个函数(如 Option::map)(Playground):

In the next example, those functions are directly passed to another function (like Option::map) (Playground):

// A function which takes a function
fn string_fn<O, F>(f: F) -> O
where
    F: FnOnce(String) -> O,
{
    f("peter".to_string())
}


string_fn(|s| println!("{}", s));  // using a clojure 
string_fn(std::mem::drop);         // using a function pointer

// Using the enum variant as function
let _: Color = string_fn(Color::Str); 

您可以在 本书的这一章.

这篇关于将枚举变量用作函数的奇怪语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆