Skip to main content
Published on

if, else if and else in Go

Share:

Introduction

Making decisions is a fundamental part of programming. In Go, the if, else if and else structures allow your program to make decisions based on conditions. In this article, you will learn how to use these structures effectively.

Basic Structure

Decision structures in Go follow a common pattern:

  1. if: Evaluates a condition and executes a block of code if the condition is true.
  2. else if: Follows the if and evaluates another condition if the previous if condition is false.
  3. else: Executes a block of code if none of the previous conditions are true.

Using if

The basic use of if is to evaluate a boolean expression:

if condition {
  // Code to be executed if the condition is true
}

Nesting conditions with else if and else

You can extend the if with additional conditions using else if and catch all other cases with else:

if condition1 {
  // Code block 1
} else if condition2 {
  // Code block 2
} else {
  // Code block 3
}

Usage Example

package main

import "fmt"

/*
  (if) condition is true {
    the code inside the if is executed
  }
  (else if) condition is true (else if only runs if the if condition is false) {
    the code inside the else if is executed
  }
  (else) no condition (only runs if the if and else if conditions are false) {
    the code inside the else is executed
  }
*/

func main() {
	x := 30

	if x == 10 {
		fmt.Println("The value of x is equal to 10.")
	} else if x == 20 {
		fmt.Println("The value of x is equal to 20.")
	} else {
		fmt.Println("The value of x is different from 10 and 20.")
	}
}

// The value of x is different from 10 and 20.

Tips and Considerations

  1. Initialisation in if: In Go, it is possible to initialise a variable inside the if declaration itself:
if x := computeSomething(); x < 10 {
  fmt.Println("Less than 10")
}
  1. Avoid Complex Conditions: Keep your conditions as simple as possible. Excessively complex conditions can make code difficult to read and maintain.
  2. Best Practices: Although Go does not require curly braces {} for single-line code blocks, it is a best practice to always use them to avoid ambiguities and make the code more readable.
  3. Alternative Structures: Sometimes it may be more appropriate to use a switch statement instead of multiple else if conditions.

Conclusion

The conditional structures if, else if and else are essential in Go programming, allowing conditional execution of code blocks. By using these structures effectively, you can make your programs more flexible and dynamic.

Happy coding!