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
}
}
}
}
}
}
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.
Top comments (1)
I didn't know you could do that, that is awesome!