Conditions
Conditions in Go
Go, like many other programming languages, allows us to make decisions in our code by using conditions. In Go, we use the if
statement to evaluate conditions.
If Statement
The basic syntax of an if
statement is as follows:
For example:
If...Else Statement
The if
statement can be extended with an else
clause, which is executed if the condition is false:
For example:
If...Else If...Else Statement
The if
statement can be extended with multiple else if
clauses to check multiple conditions:
For example:
Short If Statement
Go also provides a short form of the if
statement, which allows us to declare a local variable and execute a statement based on a condition. The syntax is as follows:
For example:
In this example, x
is declared and assigned the value of 42
within the if
statement. The if
statement checks if x
is equal to 42
and executes the associated code if the condition is true. Note that the scope of x
is limited to the if
statement.
Last updated