DEV Community

stevensonmt
stevensonmt

Posted on

5 2

Naming Nested For Loops in Rust

I've been aware of the ability to name for loops in rust for a while, but a recent project made me consider how that can make code more readable. It almost can take the place of a separate comment. My project took a string of variable length and looked for sets of keywords, trying to return the most relevant match. Some keywords and positions would carry more weight in determining relevancy.

'clauses: for clause in text.split(";") {
    'phrases: for phrase in clause.split(",") {
        'words: for word in phrase.split_whitespace() {
            'mainkeywords: for mainkey in MAIN_KEYS.iter() {
                match word.find(mainkey) {
                    Some(_) => { dostuff(word);
                                 break 'phrases 
                               },
                    _ => 'secondarykeys: for key in SECONDARY_KEYS.iter() {
                             match key.find(word) {
                                                   Some(_) => do_other_stuff(word);
                                                   break 'words 
                                                  }
                 }
              }
           }
       }
    }
Enter fullscreen mode Exit fullscreen mode

Naming the loops can have the same effect as comments while providing some useful function. I hadn't seen naming loops as a code organization/readability tool mentioned before and though I'd share. If anyone has comments on this approach in general or the code above specifically I'd love to hear them.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
thermatix profile image
Martin Becker

I didn't know you could do that, that is awesome!