Skip to content

proposal: Go 2: For Else branch #41348

@snadrus

Description

@snadrus

Whenever a Golang program needs to determine a property of all of a set/list/map/chan, it requires an "if" branch operation on a "found" variable at the end of a loop. Ex:

var found bool
for _, v := haystack {
    if v == needle {
      found = true
      break
    }
}
if !found {  
  // Operation when the set lacks the item
}

With a For-Else construct, this could save a variable, a branch, 3 lines, and has good readability:

for _, v := range haystack {
   if v == needle {
      break
   }
} else {
  // Operation when the set lacks the item   
}

The assembly would be as simple as having break jump to a label below where the end of the For loop jumps to.

Go's overloaded For construct could allow this with Range and it can work with a condition. It has no interesting meaning for unconditional looping. This idea is borrowed from Python.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLanguageChangeSuggested changes to the Go languageProposalWaitingForInfoIssue is not actionable because of missing required information, which needs to be provided.v2An incompatible library change

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions