Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass named loop labels to a macro in Rust?

Tags:

macros

rust

Using a macro that breaks out of a loop works, but I want to pass in a label to be able to define which outer loop to break out of.

Passing the argument in as an expression gave a syntax error, the only way I managed to get this to work was to pass in a block however this isn't very elegant, e.g.:

my_macro({ break 'outer; });

Is there a way to pass:

my_macro('outer);

... that can be written in the macro as break $my_label; that expands into break 'outer; ?

like image 628
ideasman42 Avatar asked Feb 05 '23 18:02

ideasman42


1 Answers

Passing it as the versatile tt (token tree) works:

macro_rules! my_break {
    ($label:tt) => { break $label; }
}

fn main() {
    'outer: loop {
        println!("Start of outer");
        loop {
            println!("Start of inner");
            my_break!('outer);
            println!("Not reachable");
        }
        println!("End of outer");
    }
    println!("End of main");
}

Playground

To future readers, there's an accepted RFC adding a lifetime specifier for macro parameters.

like image 154
Chris Emerson Avatar answered Feb 08 '23 14:02

Chris Emerson