Golang Control Structures If Switch For Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of GoLang Control Structures if, switch, for

GoLang Control Structures: if, switch, and for

GoLang, or Golang, is a statically typed, compiled programming language designed by Google. It provides straightforward and efficient control structures that include if, switch, and for for managing the flow of execution in a program.


1. if Statements

The if statement is used for decision-making in GoLang. It allows you to execute a block of code only if a specified condition is true.

Syntax:

if condition {
    // block of code to be executed if condition is true
}

With else:

if condition {
    // block of code to be executed if condition is true
} else {
    // block of code to be executed if condition is false
}

With else if:

if condition1 {
    // block of code to be executed if condition1 is true
} else if condition2 {
    // block of code to be executed if condition2 is true
} else {
    // block of code to be executed if both condition1 and condition2 are false
}

Important Points:

  • Unlike other languages, GoLang doesn't require parentheses around the condition, but curly braces {} are necessary to define the block of code.
  • The if statement can also include a short statement to execute before the condition is evaluated, which is helpful for scoping variables.
    if x := 5; x < 10 {
        fmt.Println("x is less than 10")
    }
    

2. switch Statements

The switch statement is used for multi-way branching. It replaces multiple if-else statements, making the code more organized and readable. Unlike some languages, GoLang's switch doesn't require a break statement after each case; it automatically exits the switch block at the end of a case.

Syntax:

switch expression {
case value1:
    // block of code to be executed if expression == value1
case value2:
    // block of code to be executed if expression == value2
default:
    // block of code to be executed if expression does not match any cases
}

Important Points:

  • GoLang's switch evaluates each case in order and stops executing when a case succeeds, so there's no need for a break statement.
  • The switch can be used without an expression (i.e., just switch), which can act like a clean and concise way to write long if-else-if chains.
    i := 2
    switch {
    case i%2 == 0:
        fmt.Println("Even")
    case i%2 != 0:
        fmt.Println("Odd")
    default:
        fmt.Println("Unknown")
    }
    

3. for Loops

The for loop is the only loop available in GoLang and is versatile enough to handle different situations that can be achieved with while and do-while loops in other languages.

Basic Syntax:

for initialization; condition; post {
    // block of code to be executed
}

Examples:

  • Traditional for loop:

    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
    
  • Without initialization and post:

    i := 0
    for ; i < 5; i++ {
        fmt.Println(i)
    }
    
  • while loop equivalent:

    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
    
  • Infinite loop:

    for {
        fmt.Println("This will run forever")
        break  // To avoid an infinite loop in actual code
    }
    

Important Points:

  • The for loop in GoLang is more powerful and flexible than for, while, and do-while loops in other languages. The single for keyword covers all these functionalities.
  • Unlike if and switch, parentheses around the conditional expressions are not used in for loops, but braces {} are used to define the block of code.
  • The range keyword can be used with for loops to iterate over arrays, slices, maps, and channels, providing a simpler syntax compared to traditional for loops.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement GoLang Control Structures if, switch, for

Control Structures in GoLang

if Statement

The if statement in GoLang is used to execute a block of code only if a specified condition is true.

Example: Checking age for voting eligibility

package main

import (
	"fmt"
)

func main() {
	age := 18

	if age >= 18 {
		fmt.Println("You are eligible to vote.")
	} else {
		fmt.Println("You are not eligible to vote.")
	}
}

Step-by-Step Explanation:

  1. Import the fmt package: This is used for formatting I/O operations.
  2. Declare the main function: The entry point of a Go application.
  3. Declare the age variable: Initialize it with a value (e.g., 18).
  4. if statement: Check if age is greater than or equal to 18.
    • If true, print "You are eligible to vote."
    • If false, execute the else block and print "You are not eligible to vote."
  5. Run the code: The output will be "You are eligible to vote." since age is 18.

switch Statement

The switch statement allows you to execute one block of code among many based on a variable's value.

Example: Determining the grade based on score

package main

import (
	"fmt"
)

func main() {
	score := 85

	switch {
	case score >= 90:
		fmt.Println("Grade: A")
	case score >= 80:
		fmt.Println("Grade: B")
	case score >= 70:
		fmt.Println("Grade: C")
	case score >= 60:
		fmt.Println("Grade: D")
	default:
		fmt.Println("Grade: F")
	}
}

Step-by-Step Explanation:

  1. Import the fmt package: For I/O operations.
  2. Declare the main function: Entry point of the application.
  3. Declare the score variable: Initialize it with a value (e.g., 85).
  4. switch statement: No expression is specified, so it is equivalent to switch true.
  5. case statements: Check various conditions:
    • If score >= 90, print "Grade: A".
    • If score >= 80, print "Grade: B".
    • If score >= 70, print "Grade: C".
    • If score >= 60, print "Grade: D".
    • Otherwise, print "Grade: F" (default case).
  6. Run the code: The output will be "Grade: B" since score is 85.

for Loop

The for loop in GoLang is used to repeatedly execute a block of code as long as a condition is true.

Example: Printing numbers from 1 to 10

package main

import (
	"fmt"
)

func main() {
	for i := 1; i <= 10; i++ {
		fmt.Println(i)
	}
}

Step-by-Step Explanation:

  1. Import the fmt package: For I/O operations.
  2. Declare the main function: Entry point of the application.
  3. for loop: Initialize the counter variable i to 1.
    • Continue the loop while i is less than or equal to 10.
    • Increment i by 1 after each iteration.
  4. Block of code: Print the current value of i during each iteration.
  5. Run the code: The output will be numbers from 1 to 10, each on a new line.

Summary

  • if statement: Executes code based on a boolean condition.
  • switch statement: Evaluates a variable against multiple possible values.
  • for loop: Repeats a block of code based on a condition.

You May Like This Related .NET Topic

Login to post a comment.