Go if: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
}
}
</syntaxhighlight>
</syntaxhighlight>
Note that because the lexer [[Go_Language#Semicolons|automatically inserts a semicolon]] after each token that may represent the end of statement, we always must provide the opening brace on the same line as the expression.


===If/else===
===If/else===

Revision as of 00:47, 6 July 2024

External

Internal

Overview

The if statement specifies the conditional execution of one, two or more branches according to the value of boolean expressions. Optionally, the boolean expression may be preceded by an initialization statement, which is executed before the expression is evaluated.

Simple if

if <condition> {
  <statements>
}
if x > 5 {
  println(x)
}

Note that because the lexer automatically inserts a semicolon after each token that may represent the end of statement, we always must provide the opening brace on the same line as the expression.

If/else

if <condition> {
  <statements>
} else {
  <statements>
}
if x > 5 {
  println(x)
} else {
  println("something else")
}

A special if syntax supports the Go error handling idiom that relies on functions returning errors as result value:

var result ...
var err error
if result, err = someFunc(); err != nil {
  // handle error
  return
}
// handle success
...

Avoid else in the idiom above. Do NOT write this:

if result, err := someFunc(); err {
  // handle error
  ...
} else { // BAD, avoid the "else"
  // handle success
  ...  
}

If/else if/else

if <condition> {
  <statements>
} else if <condition> {
  <statements>
} else {
  <statements>
}
if x < 5 {
  println(x)
} else if x == 5 {
  println("is 5")
} else {
  println("something else")
}