Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

How can I store a pattern in a variable in Rust?

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

This code works:

let ch = ' ';

match ch {
    ' ' | '
' | '' | '
' => 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 = ' ' | '
' | '' | '
';

let ch = ' ';

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 {
        ' ' | '
' | '' | '
' => true,
        _ => false,
    }
}

fn main() {
    let ch = ' ';

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...