如何在 Rust 的变量中存储模式? [英] How can I store a pattern in a variable in Rust?

查看:30
本文介绍了如何在 Rust 的变量中存储模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Rust 中实现一个解析器,而空白是一种常见的模式,我想在 match 模式中重用.

I'm implementing a parser in Rust and whitespace is a common pattern that I want to reuse in match patterns.

此代码有效:

let ch = ' ';

match ch {
    ' ' | '\n' | '\t' | '\r' => println!("whitespace"),
     _ => println!("token"),
}

如果我每次都需要继续指定空白模式,这将变得非常重复.我想定义一次并重用它.我想做类似的事情:

This would get really repetitive if I need to keep on specifying the whitespace pattern each time. I would like to define that once and reuse it. I want to do something like:

let whitespace = ' ' | '\n' | '\t' | '\r';

let ch = ' ';

match ch {
    whitespace => println!("whitespace"),
    _          => println!("token"),
}

编译器不喜欢 ws 赋值.它将 | 解释为二进制操作而不是交替.

The compiler does not like the ws assignment. It interprets the | as a binary operation instead of alternation.

模式可以以某种方式存储在变量中吗?有没有更好或更惯用的方法来做到这一点?

Can patterns be stored in variables somehow? Is there a better or more idiomatic way to do this?

推荐答案

模式可以以某种方式存储在变量中吗?

Can patterns be stored in variables somehow?

没有.模式是一种编译时构造,变量包含运行时概念.

No. Patterns are a compile-time construct, and variables hold run-time concepts.

有没有更好或更惯用的方法来做到这一点?

Is there a better or more idiomatic way to do this?

创建函数或方法总是避免重复代码的好方法.然后您可以将其用作保护子句:

Creating a function or method is always a good solution to avoid repeating code. You can then use this as a guard clause:

fn is_whitespace(c: char) -> bool {
    match c {
        ' ' | '\n' | '\t' | '\r' => true,
        _ => false,
    }
}

fn main() {
    let ch = ' ';

    match ch {
        x if is_whitespace(x) => println!("whitespace"),
        _ => println!("token"),
    }
}

<小时>

我还强烈建议使用现有的解析器,其中有很多,但每个人无论出于何种原因,都希望他们的 Rusthello world"能够被解析.


I'd also strongly recommend using an existing parser, of which there are a multitude, but everyone wants their Rust "hello world" to be parsing, for whatever reason.

我使用的解析库允许编写类似于此的代码,其中 whitespace 是一个知道如何解析有效空格类型的函数:

A parsing library I use allows writing code akin to this, where whitespace is a function that knows how to parse the valid types of whitespace:

sequence!(pm, pt, {
    _          = literal("if");
    ws         = whitespace;
    _          = literal("let");
    ws         = append_whitespace(ws);
    pattern    = pattern;
    ws         = optional_whitespace(ws);
    _          = literal("=");
    ws         = optional_whitespace(ws);
    expression = expression;
}, |_, _| /* do something with pieces */);

右侧的每个东西仍然是知道如何解析特定事物的独立函数.

Each of the things on the right-hand side are still individual functions that know how to parse something specific.

这篇关于如何在 Rust 的变量中存储模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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