Naming Nested For Loops in Rust

stevensonmt

stevensonmt

Posted on May 10, 2018

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.

💖 💪 🙅 🚩
stevensonmt
stevensonmt

Posted on May 10, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

December Surely Looks Busy!
opensource December Surely Looks Busy!

November 29, 2024

December Surely Looks Busy!
opensource December Surely Looks Busy!

November 29, 2024

Daemons on macOS with Rust
undefined Daemons on macOS with Rust

November 29, 2024