Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #223 for else loop

Loop through list items checking a condition. Do something else if no matches are found.

A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.

These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.

#include <list>
bool found = false;
for (const auto item : items) {
  if (item == "baz") {
    baz();
    found = true;
    break;
  }
}
if (!found) {
  DoSomethingElse();
}
items := []string{"foo", "bar", "baz", "qux"}

for _, item := range items {
    if item == "baz" {
        fmt.Println("found it")
        goto forelse
    }
}
{
    fmt.Println("never found it")
}
forelse:
Found := False;
for Item in Items do
begin
  if Item.MatchesCondition then
  begin
    Found := True;
    Break;
  end;
end;
if not Found then 
  DoSomethingElse;
items = ['foo', 'bar', 'baz', 'qux']

for item in items:
    if item == 'baz':
        print('found it')
        break
else:
    print('never found it')
items = ['foo', 'bar', 'baz', 'qux']
puts items.any?("baz") ? "found it" : "never found it"
let items: &[&str] = &["foo", "bar", "baz", "qux"];

let mut found = false;
for item in items {
    if item == &"baz" {
        println!("found it");
        found = true;
        break;
    }
}
if !found {
    println!("never found it");
}

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

Ruien