Learnmonkey Learnmonkey Logo

Go If and Else

If Statements

If statements are when we want to execute some lines of code only when a specific condition is met. Below is the basic structure of a Go if statement:


if [condition] {
    // do something if the condition is met
}
    

We replace [condition] with the condition we want to test. Then, inside the curly brackets, we put our code. The code is only run if the condition is met.

Else Statements

Sometimes, we want something to happen when a condition is met, but something else to happen if the condition is not met. To do this, we can use else statements. Below is the syntax of the if and else statement:


if [condition] {
    // do something if the condition is met
} else {
    // do something if the condition is not met
}
    
The last curly bracket of the if statement and the start of the else statement have to be on the same line! Otherwise, you'd get an error.
You can have an if statement without an else, but you can't have an else statement without an if!

Else If Statements

Sometimes, we want to do something if none of the previous conditions are met, but the condition is met. That is what the else if statement is for. Below is an example:


if [condition 1] {
    // do something if condition 1 is met
} else if [condition 2] {
    // do something if condition 1 is not met, but condition 2 is met
} else if [condition 3] {
    // do something is condition 1 and 2 are not met, but condition 3 is met
} else {
    // do something if condition 1, 2, and 3 are all not met
}
    

We can chain as many else if statements together as we want.

The last curly bracket of each statement has to be on the same line as the next statement.
You can have an if and else if statement without an else statement, but you can't have an else if statement without an if!

Nested If Statements

You can have nested if statements, but it's often better to use logical operators. For example:


if x < 6 {
    if x < 4 {
        // code here only executes if x is smaller than 6 and 4
    }
}
    

The above code could be replaced with the following using logical operators:


if x < 6 && x < {
    // code here only executes if x is smaller than 6 and 4
}