Golang Control Structures If Switch For Complete Guide
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 abreak
statement. - The
switch
can be used without an expression (i.e., justswitch
), which can act like a clean and concise way to write longif-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 thanfor
,while
, anddo-while
loops in other languages. The singlefor
keyword covers all these functionalities. - Unlike
if
andswitch
, parentheses around the conditional expressions are not used infor
loops, but braces{}
are used to define the block of code. - The
range
keyword can be used withfor
loops to iterate over arrays, slices, maps, and channels, providing a simpler syntax compared to traditionalfor
loops.
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
fmt
package: This is used for formatting I/O operations. - Declare the
main
function: The entry point of a Go application. - Declare the
age
variable: Initialize it with a value (e.g., 18). if
statement: Check ifage
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."
- 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:
- Import the
fmt
package: For I/O operations. - Declare the
main
function: Entry point of the application. - Declare the
score
variable: Initialize it with a value (e.g., 85). switch
statement: No expression is specified, so it is equivalent toswitch true
.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).
- If
- 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:
- Import the
fmt
package: For I/O operations. - Declare the
main
function: Entry point of the application. for
loop: Initialize the counter variablei
to 1.- Continue the loop while
i
is less than or equal to 10. - Increment
i
by 1 after each iteration.
- Continue the loop while
- Block of code: Print the current value of
i
during each iteration. - 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.
Login to post a comment.