Boilerplate reduction - labels for if-expressions

⚓ Rust    📅 2025-09-04    👤 surdeus    👁️ 14      

surdeus

Warning

This post was published 89 days ago. The information described in this article may have changed.

It would be nice if we could label any scope, and then break from them. Similar to (Break with label), but with a better example: I had a complicated set of nested if branching and wanted to break out of them


'my_label : if my_bool
{  // ... do stuff to see if we need to do something else instead
  if stop_this_stuff
  { break 'my_label;
  }
}

it should be equivalent to :

'my_label : loop
{  if my_bool
  {  // ... do stuff to see if we need to do something else instead
    if stop_this_stuff
    { break 'my_label;
    }
  }
  break 'my_loop;
}

(which is the current workaround, I also wrote a macro to generate this, but it looks too ugly)

I guess I could just turn my if-conditions into while-loops that break at the end of the loop. But implementing labels for 'if' statements should be incredibly straightforward for compiler developers, given the equivalence with other syntax.

4 posts - 3 participants

Read full topic

🏷️ Rust_feed