Table of Contents
- Introduction
- Prerequisites
- Control Statements in Go
-
If Statement - Basic If Statement - If-Else Statement - If-Else If-Else Statement
-
Switch Statement - Basic Switch Statement - Switch with Multiple Cases - Switch with an Expression
-
For Loop - Basic For Loop - For Loop with a Condition - For Loop with Range
- Conclusion
Introduction
Welcome to the comprehensive guide on control statements in Go programming language! In this tutorial, we will cover the basics of control statements and provide practical examples to help you understand their usage. By the end of this tutorial, you will be able to write Go programs that use if statements, switch statements, and for loops to control the flow of execution.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Go syntax and how to write simple Go programs. It is also beneficial to have Go installed on your system. If you haven’t installed Go yet, please visit the official Go website (https://golang.org/doc/install) for installation instructions.
Control Statements in Go
Control statements enable us to control the flow of execution in a program. They allow us to make decisions, perform repetitive tasks, and handle different cases efficiently. In Go, the main control statements are the if statement, switch statement, and for loop.
If Statement
The if statement allows us to conditionally execute a block of code. It evaluates a boolean expression and executes the code inside the if block if the expression is true.
Basic If Statement
The basic if statement in Go follows this syntax:
if condition {
// Code to be executed if the condition is true
}
Let’s see an example:
package main
import "fmt"
func main() {
var num int = 10
if num > 0 {
fmt.Println("The number is positive")
}
}
Output:
The number is positive
In the above example, we check if the variable num
is greater than 0 using the if statement. If the condition is true, we print “The number is positive”.
If-Else Statement
The if-else statement allows us to execute one block of code if the condition is true and another block of code if the condition is false.
if condition {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Let’s modify our previous example to include an else block:
package main
import "fmt"
func main() {
var num int = -5
if num > 0 {
fmt.Println("The number is positive")
} else {
fmt.Println("The number is non-positive")
}
}
Output:
The number is non-positive
In the above example, if the condition num > 0
evaluates to false, the code inside the else block will be executed.
If-Else If-Else Statement
We can use multiple else if statements to handle multiple conditions using the if-else if-else statement.
if condition1 {
// Code to be executed if condition1 is true
} else if condition2 {
// Code to be executed if condition2 is true
} else {
// Code to be executed if all conditions are false
}
Here’s an example:
package main
import "fmt"
func main() {
var num int = 0
if num > 0 {
fmt.Println("The number is positive")
} else if num < 0 {
fmt.Println("The number is negative")
} else {
fmt.Println("The number is zero")
}
}
Output:
The number is zero
In the above example, we check for three conditions: num > 0, num < 0, and num == 0. Depending on the value of num
, the corresponding code block will be executed.
Switch Statement
The switch statement allows us to select one of many code blocks to be executed based on the value of an expression. It simplifies code readability when handling multiple cases.
Basic Switch Statement
The basic switch statement in Go follows this syntax:
switch expression {
case value1:
// Code to be executed if the expression equals value1
case value2:
// Code to be executed if the expression equals value2
default:
// Code to be executed if none of the cases match
}
Let’s see an example:
package main
import "fmt"
func main() {
var dayOfWeek int = 3
switch dayOfWeek {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
default:
fmt.Println("Weekend")
}
}
Output:
Wednesday
In the above example, we use the switch statement to match the value of dayOfWeek
with the corresponding case and execute the respective code block.
Switch with Multiple Cases
We can list multiple cases together if they have the same code block.
switch expression {
case value1, value2, value3:
// Code to be executed if the expression equals either value1, value2, or value3
default:
// Code to be executed if none of the cases match
}
Here’s an example:
package main
import "fmt"
func main() {
var grade string = "A"
switch grade {
case "A", "B":
fmt.Println("Excellent")
case "C", "D":
fmt.Println("Good")
default:
fmt.Println("Fail")
}
}
Output:
Excellent
In the above example, if the value of grade
is either “A” or “B”, the code block associated with the case “A”, “B” will be executed.
Switch with an Expression
We can use an expression instead of a simple value in the switch statement.
switch {
case expression1:
// Code to be executed if expression1 is true
case expression2:
// Code to be executed if expression2 is true
default:
// Code to be executed if none of the cases match
}
Let’s see an example:
package main
import "fmt"
func main() {
var age int = 25
switch {
case age < 18:
fmt.Println("Underage")
case age >= 18 && age < 65:
fmt.Println("Adult")
default:
fmt.Println("Senior Citizen")
}
}
Output:
Adult
In the above example, we use an expression to determine the code block to be executed based on the age of a person.
For Loop
The for loop allows us to iterate over a sequence of values or repeat a block of code a certain number of times.
Basic For Loop
The basic for loop in Go follows this syntax:
for initialization; condition; post {
// Code to be executed in each iteration
}
Here’s an example that prints the numbers from 1 to 5 using a for loop:
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
Output:
1
2
3
4
5
In the above example, the for loop initializes i
to 1, checks if i
is less than or equal to 5, and increments i
by 1 in each iteration.
For Loop with a Condition
We can use a for loop with just a condition, similar to a while loop in other programming languages.
for condition {
// Code to be executed in each iteration
}
Let’s see an example that prints the numbers from 1 to 5:
package main
import "fmt"
func main() {
var i int = 1
for i <= 5 {
fmt.Println(i)
i++
}
}
Output:
1
2
3
4
5
In the above example, the for loop continues until the condition i <= 5
evaluates to false.
For Loop with Range
We can use a for loop with the range
keyword to iterate over elements of an array, slice, string, or map.
for index, value := range collection {
// Code to be executed for each index-value pair
}
Here’s an example that prints the elements of an array:
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4, 5}
for index, value := range arr {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
Output:
Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5
In the above example, we use the range keyword to iterate over the elements of the array arr
and print their values along with their respective indices.
Conclusion
In this tutorial, we covered control statements in Go, including the if statement, switch statement, and for loop. We learned how to use these statements to make decisions, handle multiple cases, and iterate over sequences of values. By mastering these control statements, you can write more powerful and flexible Go programs. Try experimenting with different examples and explore more advanced use cases to deepen your understanding of control statements in Go.