A Complete Guide - 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
ifstatement 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
switchevaluates each case in order and stops executing when a case succeeds, so there's no need for abreakstatement. - The
switchcan be used without an expression (i.e., justswitch), which can act like a clean and concise way to write longif-else-ifchains.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
forloop:for i := 0; i < 5; i++ { fmt.Println(i) }Without initialization and post:
i := 0 for ; i < 5; i++ { fmt.Println(i) }whileloop 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
forloop in GoLang is more powerful and flexible thanfor,while, anddo-whileloops in other languages. The singleforkeyword covers all these functionalities. - Unlike
ifandswitch, parentheses around the conditional expressions are not used inforloops, but braces{}are used to define the block of code. - The
rangekeyword can be used withforloops to iterate over arrays, slices, maps, and channels, providing a simpler syntax compared to traditionalforloops.
Online Code run
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:
- Import the
fmtpackage: This is used for formatting I/O operations. - Declare the
mainfunction: The entry point of a Go application. - Declare the
agevariable: Initialize it with a value (e.g., 18). ifstatement: Check ifageis greater than or equal to 18.- If true, print "You are eligible to vote."
- If false, execute the
elseblock and print "You are not eligible to vote."
- Run the code: The output will be "You are eligible to vote." since
ageis 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:
- Import the
fmtpackage: For I/O operations. - Declare the
mainfunction: Entry point of the application. - Declare the
scorevariable: Initialize it with a value (e.g., 85). switchstatement: No expression is specified, so it is equivalent toswitch true.casestatements: 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).
- If
- Run the code: The output will be "Grade: B" since
scoreis 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:
- Import the
fmtpackage: For I/O operations. - Declare the
mainfunction: Entry point of the application. forloop: Initialize the counter variableito 1.- Continue the loop while
iis less than or equal to 10. - Increment
iby 1 after each iteration.
- Continue the loop while
- Block of code: Print the current value of
iduring each iteration. - Run the code: The output will be numbers from 1 to 10, each on a new line.
Summary
ifstatement: Executes code based on a boolean condition.switchstatement: Evaluates a variable against multiple possible values.forloop: Repeats a block of code based on a condition.
Login to post a comment.