Go if: Difference between revisions
Jump to navigation
Jump to search
(Created page with "The <code>if</code> statement specifies the conditional execution of two branches according to the value of a boolean expression. Optionally, the boolean expression may be preceded by another statement, which is executed before the expression is evaluated. ===Simple If=== {{External|https://go.dev/ref/spec#If_statements}} <syntaxhighlight lang='go'> if <condition> { <statements> } </syntaxhighlight> <syntaxhighlight lang='go'> if x >...") |
No edit summary |
||
Line 1: | Line 1: | ||
=Internal= | |||
* [[Go_Language#if_Statement|Go Language]] | |||
=Overview= | |||
The <code>if</code> statement specifies the conditional execution of two branches according to the value of a boolean expression. Optionally, the boolean expression [[#Statement_Precedes_Expression |may be preceded by another statement]], which is executed before the expression is evaluated. | The <code>if</code> statement specifies the conditional execution of two branches according to the value of a boolean expression. Optionally, the boolean expression [[#Statement_Precedes_Expression |may be preceded by another statement]], which is executed before the expression is evaluated. | ||
===Simple If=== | ===Simple If=== |
Revision as of 00:19, 6 July 2024
Internal
Overview
The if
statement specifies the conditional execution of two branches according to the value of a boolean expression. Optionally, the boolean expression may be preceded by another statement, which is executed before the expression is evaluated.
Simple If
if <condition> {
<statements>
}
if x > 5 {
println(x)
}
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")
}