Learn Go: Golang Control Flow Statements: If, If-Else #8

In this tutorial you'll learn how to write decision-making conditional statements used to perform different actions in Golang.

Gopher

Lets go!!

Published · Jan 15 2020


If statements are used to specify whether a block of code should be executed or not depending on a given condition.

If Statement

Following is the syntax of if statements in Golang -
if(condition) { // Code to be executed if the condition is true. }

Here is a simple example -
package main import "fmt" func main() { var x = 25 if(x % 5 == 0) { fmt.Printf("%d is a multiple of 5\n", x) } }


Note that, You can omit the parentheses () from an if statement in Golang, but the curly braces {} are mandatory -
var y = -1 if y < 0 { fmt.Printf("%d is negative\n", y) }

You can combine multiple conditions using short circuit operators && and || like so -
var age = 21 if age >= 17 && age <= 30 { fmt.Println("My Age is between 17 and 30") }

. . .

If-Else Statement

An if statement can be combined with an else block. The else block is executed if the condition specified in the if statement is false -
if condition { // code to be executed if the condition is true } else { // code to be executed if the condition is false }

Here is a simple example -
package main import "fmt" func main() { var age = 18 if age >= 18 { fmt.Println("You're eligible to vote!") } else { fmt.Println("You're not eligible to vote!") } }


. . .

If-Else-If Chain

if statements can also have multiple else if parts making a chain of conditions like this -
package main import "fmt" func main() { var BMI = 21.0 if BMI < 18.5 { fmt.Println("You are underweight"); } else if BMI >= 18.5 && BMI < 25.0 { fmt.Println("Your weight is normal"); } else if BMI >= 25.0 && BMI < 30.0 { fmt.Println("You're overweight") } else { fmt.Println("You're obese") } }


. . .

If with a short statement

An if statement in Golang can also contain a short declaration statement preceding the conditional expression -
if n := 10; n%2 == 0 { fmt.Printf("%d is even\n", n) }

The variable declared in the short statement is only available inside the if block and it’s else or else-if branches -
if n := 15; n%2 == 0 { fmt.Printf("%d is even\n", n) } else { fmt.Printf("%d is odd\n", n) }

Note that, If you’re using a short statement, then you can’t use parentheses. So the following code will generate a syntax error -
// You can't use parentheses when `if` contains a short statement if (n := 15; n%2 == 0) { // Syntax Error }
. . .

Conclusion

That’s all folks. In this article, you learned how to work with control flow statements like if, if-else in Golang.

In the next article, You’ll learn how to define functions in Go. See you in the next post!
. . .

. . .
Chris Gregori

Oct 19 2019

Write your response...

On a mission to build Next-Gen Community Platform for Developers