rust - 将枚举变体用作函数的这种奇怪语法是什么?

标签 rust rust-proc-macros

下面是examplesyn::parse 的 mod 文档给出。

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 特定语法规则的文档?

最佳答案

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

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):

// 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); 

您可以在 this chapter of the book 中找到有关此功能的更多信息.

关于rust - 将枚举变体用作函数的这种奇怪语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56992624/

相关文章:

rust - 如何从vec中的枚举中获取值?

rust - 如何获取传递给内部属性宏的模块内容?

parsing - 在 proc 宏派生上将属性转换为标识符

struct - 如何以编程方式获取结构的字段数?

rust - `::parse()` 在结构上做什么?

data-structures - 将 u8 缓冲区转换为 Rust 中的结构

mysql - 特征 `diesel::Expression` 没有为 `f64` 实现

r - 如何从Rust程序宏生成文件?

rust - 如何使用亲爱的解析带有嵌套参数的属性?

time - 如何以亚秒级精度计时操作的持续时间?