Control Flow

If Statement in Go

The if else block controls decision making by checking true/false statements resulting in different executions of code, depending on if the result is true and if the result is false.

There are three parts to the if-else block: if, else if, and else.


Syntax
if booleanExpression {
    //do something
} else if someStatement; booleanExpression2 { //statements can precede boolean expressions
    //do something
} else {
    //do this if none of the above are true
}

Notes

booleanExpression(s) are those that result in either a true or false output (also called conditional statements). They are created using comparing operators (==, >, =, <=, !=).

Statements can precede the Boolean expression. This is often used when error checking.

There can also be multiple Boolean expressions. The Boolean expressions are connected through logical operators (&&, ||, !).


Example
if counter++; counter >= 30 { //assuming counter variable is declared as int
    fmt.Println("Counter is greater than or equal to 30."); //assuming fmt declared
} 
else if counter == 20 { 
    System.out.print("Counter is at 20."); 
    counter++; 
} 
else { 
    counter++; 
}

< Structs   |   Switch Case >

© 2018 SyntaxDB. All Rights Reserved.