Go if else
In Go, the if-else
statement is used to control the program flow based on a Boolean condition. The syntax of the if-else
statement is as follows:
if condition { // code to be executed if the condition is true } else { // code to be executed if the condition is false }
The condition
in the if
statement is a Boolean expression that evaluates to either true
or false
. If the condition is true
, the code block immediately following the if
statement is executed. If the condition is false
, the code block immediately following the else
statement is executed.
Here's an example of using the if-else
statement in Go:
x := 10 if x < 0 { fmt.Println("x is negative") } else if x == 0 { fmt.Println("x is zero") } else { fmt.Println("x is positive") }
In this example, the program checks the value of the variable x
. If x
is less than zero, the message "x is negative" is printed. If x
is equal to zero, the message "x is zero" is printed. If x
is greater than zero, the message "x is positive" is printed.
You can also use the if
statement without the else
block, as shown in the following example:
x := 10 if x > 5 { fmt.Println("x is greater than 5") }
In this example, the program checks the value of the variable x
. If x
is greater than 5, the message "x is greater than 5" is printed. If x
is less than or equal to 5, no code is executed after the if
statement.
It's worth noting that Go also supports the if
statement with a short statement, which allows you to declare and initialize a variable in the same line as the condition. For example:
if x := 10; x > 5 { fmt.Println("x is greater than 5") }
In this example, the program declares and initializes the variable x
with a value of 10 in the same line as the if
statement. If x
is greater than 5, the message "x is greater than 5" is printed.