How to save a template in a variable in Rust?

I use a parser in Rust, and spaces are a common pattern that I want to reuse in match patterns.

This code works:

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

This will really repeat if I need to specify a space pattern each time. I would like to define it once and reuse it. I want to do something like:

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

The compiler does not like the purpose of ws . He interprets | as a binary operation instead of interleaving.

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

+5
source share
1 answer

Can templates be stored in variables somehow?

No. Templates are a compile-time construct, and variables contain runtime concepts.

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

Creating a function or method is always a good solution to avoid code repetition.

 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"), } } 

I also highly recommend using an existing parser, of which there are many , but everyone wants their rust "hello world" to parse for any reason.

The parsing library I use allows me to write code close to this, where whitespace is a function that can analyze valid types of spaces:

 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 side still has separate functions that can parse something specific.

+10
source

Source: https://habr.com/ru/post/1265447/


All Articles