Mark
Mark

Reputation: 1174

What does a golang for { ..block.. } without conditions do?

I'm a golang neophyte and I've come across a rather interesting control structure which doesn't follow the classical imperative for-loop construct. I've been unable to locate on documentation on the structure either. The following is the code in question:

  for {
    // read each incoming message
    m, err := getMessage(ws)
    if err != nil {
      log.Fatal(err)
    }   

    // see if we're mentioned
    if m.Type == "message" && strings.HasPrefix(m.Text, "<@"+id+">") {
      // if so try to parse if
      ans := lookup(session, m.Text)
      if len(ans)>0 {
        // looks good, get the quote and reply with the result
        go func(m Message) {
          for _, def := range ans {
            if len(def[1]) > 0 { 
              m.Text = "*" + def[0] + " " + def[1] + "*: " + def[2]
            } else {
              m.Text = "*" + def[0] + "*: " + def[2]
            }   
            postMessage(ws, m)
            }   
        }(m)
        // NOTE: the Message object is copied, this is intentional
      } else {
        // huh?
        m.Text = fmt.Sprintf("sorry, that does not compute\n")
        postMessage(ws, m)
      }   
    }   
  }

Does the loop construct just loop forever or is there an eventing system binding behind the scenes?

Upvotes: 22

Views: 8588

Answers (2)

peterSO
peterSO

Reputation: 166529

The Go Programming Language Specification

For statements

A "for" statement specifies repeated execution of a block. The iteration is controlled by a condition, a "for" clause, or a "range" clause.

ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
Condition = Expression .

In its simplest form, a "for" statement specifies the repeated execution of a block as long as a boolean condition evaluates to true. The condition is evaluated before each iteration. If the condition is absent, it is equivalent to the boolean value true.

If the condition is absent, for example, for { ... }, it is equivalent to the boolean value true, for example for true { ... }. It is sometimes referred to as an infinite loop. Therefore, you will need another mechanism, such as break or return, to terminate the loop.

The documentation for the for statement is the The Go Programming Language Specification.

Upvotes: 27

Ainar-G
Ainar-G

Reputation: 36189

for without any additional statements is basically the same as while (true) in other languages, an infinite loop.

Upvotes: 13

Related Questions