Golang if else Statements

Introduction

In Golang, an if statement is utilized to run a block of code only when a specific condition is met. This is essential for directing the program’s flow and enables developers to make choices based on particular conditions.

Basic If Statement

The basic syntax of an if statement in Golang is as follows:

Syntax of the If Statement

Let us understand the above if statement syntax,

if condition {
   //The code block executes if the condition is true
}
  • if: It starts with the “if” keyword, which checks whether the conditional code is true or false.
  • condition: It contains the conditional code, which evaluates to either true or false.
  • {}: Curly brackets contain the block of code that is executed if the condition is true; otherwise, the code is not executed.

Example of if statement

let’s say we have a variable age and we want to check if it is greater than or equal to 18. The if statement would look like this:
Golang code :

age := 20
if age >= 18 {
   fmt.Println("You are eligible to register.")
}

In this example, since age is 20, which is greater than 18, the output will be “You are an adult.”
For additional examples of if statements, feel free to check out my GitHub repository.

if-with-Short-Statement

In Golang, the if statement can include a short statement before the condition. This feature allows you to initialize or declare variables that are scoped to the if statement, which can be particularly useful for concise and clear code.

Syntax of the if-with-Short-Statement

The basic syntax of an if statement with a short statement is as follows:

if initialization; condition {
   //The code block executes if the condition is true
}

Explanation

  • initialization: This is a short statement that can declare or initialize variables. It is executed before the condition is evaluated.
  • condition: It contains the conditional code, which evaluates to either true or false.
  • {}: Curly brackets contain the block of code that is executed if the condition is true; otherwise, the code is not executed.

The variables specified in the short statement are limited to the scope of the if statement and its related blocks, which include any else or else-if blocks. Most developers use it for limited scope and when the variable will never be used afterward.

Example of the if-with-Short-Statement

  if file, err := os.Open("example.txt"); err == nil {
       fmt.Println("File opened successfully")
       // Make sure to close the file
       file.Close()
   } else {
       fmt.Println("Error opening file:", err)
   }

Explanation of the File Handling Example

Short Statement:

  • file, err := os.Open(“example.txt”): The short statement attempts to open a file named “example.txt” and assigns the file handle to the file and the error (if any) to err.

Condition:

  • err == nil: The condition checks if the error err is nil, indicating that the file was opened successfully.

Code Block:

  • If err == nil, the code block prints “File opened successfully” and closes the file using the file.Close().
  • If err != nil, the else block prints “Error opening file:” followed by the error message.

For more if with short statement examples, you can visit my GitHub repository

if-else Statement

An if-else statement in Go allows you to choose between two different actions based on a condition. If the condition is true, the code inside the if block runs. If the condition is false, the code inside the else block runs.

Syntax of the if-else Statement

The basic syntax of an if-else statement in Go is as follows:

if condition {
   // The code block executes if the condition is true
} else {
   // The code block executes if the condition is false
}
Let us understand the above if-else statement syntax, 
  • if: It starts with the “if” keyword, which checks whether the conditional code is true or false.
  • condition: It contains the conditional code, which evaluates to either true or false.
  • {}: curly bracket of “if” and “else” keywords contains code blocks of true and false conditions respectively.
  • else: when the condition is false, else’s code block executes.

Example of the if-else Statement

func main() {
   number := -10

   if number >= 0 {
       fmt.Println("The number is positive.")
   } else {
       fmt.Println("The number is negative.")
   }
}

In this example:

  1. We define a variable number with a value of -10.
  2. The if statement checks if the number is greater than 0.
    • If this condition is true, it prints “The number is positive.”
    • If this condition is false  (in above example), it prints “The number is negative.”

Since the number is -10, which is less than 0, the output will be: “The number is negative.”

For more if-else examples, you can visit my GitHub repository

Nested if Statement

An if statement nested within another if statement is known as a nested if statement. This enables you to verify several conditions in a hierarchical fashion, so circumstances that come after are only considered valid if the criteria that came before them are valid.

Syntax of the Nested “if” Statement

The syntax for nested if statements in Go is as follows:

if condition1 {
   // code block to execute if condition1 is true
   if condition2 {
       // code block to execute if condition1 and condition2 are true
   }
}

Explanation:

  • if condition1 { … }: The outer if statement. If condition1 is true, the code block inside this statement is executed.
  • Inside the outer if statement, there’s another if statement: if condition2 { … }. This is the nested if statement.
    • If condition 1 is true, then condition 2 is evaluated.
    • If both condition1 and condition2 are true, the code block inside the nested if statement is executed.

Example of a Nested “if” Statement

Let’s consider an example where we check if a number is positive and then check if it is even:
Golang code

func main() {
   number := 8
   if number > 0 {
       fmt.Println("The number is positive.")
       if number%2 == 0 {
           fmt.Println("The number is also even.")
       }
   }
}

Explanation of the Example

  1. Outer if Statement:
    • if number > 0: This checks if the variable number is greater than 0.
    • If the number is greater than 0, the message “The number is positive.” is printed.
  2. Nested if Statement:
    • Inside the outer if statement, there’s another if statement: if number%2 == 0.
    • This checks if the number is even by evaluating the condition number%2 == 0.
    • If the number is positive and even, the message “The number is also even.” is printed.

Syntax of a Nested if-else Statement

The syntax for nested if-else statements in Go is as follows:

if condition1 {
   // The code block executes if condition1 is true
   if condition2 {
       //The code block executes if condition1 and condition2 are true
   } else {
       //The code block executes if condition1 is true and condition2 is false
   }
} else {
   //The code block executes if condition1 is false
}

Explanation

  1. if condition1 { … }: The outer if statement. If condition1 is true, the code block inside this statement is executed.
  2. Inside the outer if statement, there is another if-else statement:
    • if condition2 { … }: This nested if statement is evaluated if condition1 is true.
        • if condition2 is true, the corresponding code block is executed.
        • else { … }: If condition2 is false, the code block inside the else statement is executed
  3. else { … }: This outer else block is executed if condition1 is false.

Example of a Nested if-else Statement

Let’s consider an example where we check if a number is positive, and if it is, we further check if it is even or odd:

func main() {
   number := 7

   if number > 0 {
       fmt.Println("The number is positive.")

       if number%2 == 0 {
           fmt.Println("The number is even.")
       } else {
           fmt.Println("The number is odd.")
       }
   } else {
       fmt.Println("The number is not positive.")
   }
}

Explanation of the Example

  1. Outer if-else Statement:
    • if number > 0: This checks if the variable number is greater than 0.
    • If number is greater than 0, the message “The number is positive.” is printed.
    • If number is not greater than 0, the message “The number is not positive.” is printed.

2.Nested if-else Statement:

    • Inside the outer if statement, there’s another if-else statement: if number%2 == 0.
    • This checks if number is even by evaluating the condition number%2 == 0.
    • If number is even, the message “The number is even.” is printed.
    • If number is not even (i.e., it is odd), the message “The number is odd.” is printed.

For more examples, you can visit my GitHub repository

Introduction to else if

The “else if” construct in Golang allows you to evaluate multiple conditions sequentially until one of them evaluates to true, executing the corresponding block of code. It’s useful for handling cascading conditions.

Syntax of else if

The syntax for “else if” in Golang is:

if condition1 {
   // code block 1
} else if condition2 {
   // code block 2
} else if condition3 {
   // code block 3
} else {
   // default code block
}

Example of else if

func main() {
   num := 20

   if num > 50 {
       fmt.Println("Number is greater than 50")
   } else if num > 30 {
       fmt.Println("Number is greater than 30")
   } else if num > 10 {
       fmt.Println("Number is greater than 10")
   }
}

In this example:

  • If num is greater than 50, it prints “Number is greater than 50”.
  • If num is between 30 and 50 (exclusive), it prints “Number is greater than 30”.
  • If num is between 10 and 30 (exclusive), it prints “Number is greater than 10”.
  • If num is 10 or less, nothing is printed because there’s no “else” block following the “else if” chain.

For more else if examples, you can visit my GitHub repository

Switch Statement

In Golang, a switch statement lets you choose which of the numerous code blocks to run. When comparing one expression against many values, it’s a more understandable option than using numerous if-else expressions. Golang’s switch statements are flexible and work with a wide range of data types, including string, integer, and custom data types.

(Note: The switch statement is generally faster than if-else statements in Golang, with a simple if-else chain taking around 10-20 ns per iteration and a switch statement with 10 cases taking around 2-5 ns per iteration. However, the actual performance difference may vary depending on the specific use case, input data, and CPU architecture.)

Syntax of a Switch Statement

The basic syntax of a switch statement in Golang is as follows:

switch expression {
case value1:
   //The code block executes if expression == value1
case value2:
   //The code block executes if expression == value2
default:
   //The code block executes if the expression does not match any case
}
Explanation
  • switch expression: This starts the switch statement. The expression is evaluated against the case values previously defined.
  • case value1: if the expression matches value1, the corresponding code block is executed.
  • default: This optional block executes if the expression doesn’t match any of the cases. It acts like the final else in an if-else chain.

Example of Switch Statement

Let’s look at an example where a switch statement is used to print a message based on the day of the week:

func main() {
    day := "Tuesday"

    switch day {
    case "Monday":
        fmt.Println("Start of the work week.")
    case "Tuesday":
        fmt.Println("Second day of the work week.")
    case "Wednesday":
        fmt.Println("Midweek.")
    case "Thursday":
        fmt.Println("Almost the weekend.")
    case "Friday":
        fmt.Println("Last workday of the week.")
    case "Saturday", "Sunday":
        fmt.Println("Weekend!")
    default:
        fmt.Println("Not a valid day.")
    }
}

Explanation of the Example

  1. switch Statement:
    • switch day { … }: The switch statement evaluates the variable day.
    • case “Monday”:: If the day is “Monday”, the message “Start of the work week.” is printed.
    • case “Tuesday”:: If the day is “Tuesday”, the message “Second day of the work week.” is printed.
    • case “Saturday”, “Sunday”:: Multiple values in a case statement. If the day is either “Saturday” or “Sunday”, the message “Weekend!” is printed.
    • default: If the day does not match the specified cases, the message “Not a valid day.” is printed.

For more switch examples, you can visit my GitHub repository

Switch Without an Expression

In Go, you can also use a switch statement without an expression, which can be useful for more complex conditional logic:

func main() {
   number := 15

   switch {
   case number < 10:
       fmt.Println("The number is less than 10.")
   case number >= 10 && number < 20:
       fmt.Println("The number is between 10 and 20.")
   default:
       fmt.Println("The number is 20 or greater.")
   }
}

For more switch examples, you can visit my GitHub repository

Best Practices

  1. When you want to use a single/limited scope variable, use if with short statement
  2. Use a switch statement instead of multiple else if chains
  3. It is a best practice to handle each error with the help of if block