Go Conditionals
Conditionals, primarily the if, else, and else if statements, are used to execute based on whether an expression evaluates to true or false.
Conditionals can be nested elsewhere such as inside the switch and for statements.
The if Statement
The if statement is mostly associated with conditionals. The code block inside an if statement executes if a condition evaluates true. Otherwise, it is skipped.
Syntax
if condition {
statements
}
If the condition is true, the statements inside the code block will be executed. Execution continues after the if block regardless of the value of condition.
The if statement in Go also allows a small statement to be executed before the condition is evaluated. In this respect, it is similar to the for statement.
if statement; condition {
statements
}
Example
i := 0if i++; i > 0 {fmt.Println("This line will be executed.")}
The else Statement
The else statement provides an optional block of code that executes if all prior conditions evaluate to false.
Syntax
if condition {
statements_1
} else {
statements_2
}
If condition is true, statements_1 will execute. If condition is false, statements_2 will execute instead. Execution then continues after the else block.
The else if Statement
The addition of else if statements allow additional conditions to be tested if the prior ones are false. Each is associated with its own block of code to execute if its condition is true.
Syntax
if condition_1 {
statements_1
} else if condition_2 {
statements_2
} else {
statements_3
}
The control flow logic of the code below can be broken down like this:
- If
condition_1istrue,statements_1will execute. - Else, if
condition_1isfalseandcondition_2istrue,statements_2will be executed instead. - However, if neither condition is
true,statements_3will execute.
Execution then continues after the else block. There can be any number of else if statements, and the final else is optional.
Codebyte Example
For further information on writing conditional expressions see the sections “Comparison Operators” and “Logical Operators” under Go Operators
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Back-end developers deal with the hidden processes that run behind the scenes, building APIs and databases that power the front-end.
- Includes 41 Courses
- With Professional Certification
- Beginner Friendly.105 hours
- Learn how to use Go (Golang), an open-source programming language supported by Google!
- Beginner Friendly.6 hours