In programming, control structures are essential for managing the flow of execution in your code. They allow you to make decisions and repeat actions based on certain conditions. In this tutorial, we will explore three fundamental control structures in Go: if statements, switch cases, and loops (for).
An if statement is used to execute a block of code only if a specified condition is true. It can also include an optional else clause to handle the case where the condition is false.
if condition {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
### Switch Cases
A `switch` statement provides a more concise way to check multiple conditions. It compares a variable against several possible values and executes the code block corresponding to the first matching case.
#### Syntax
```go
switch expression {
case value1:
// Code to execute if expression == value1
case value2:
// Code to execute if expression == value2
default:
// Code to execute if no cases match
}
### Loops
Go has a single looping construct, the `for` loop. It can be used in three different ways: basic for loop, while-like loop, and infinite loop.
#### Basic For Loop
```go
for initialization; condition; post {
// Code to execute repeatedly
}
#### While-Like Loop
```go
for condition {
// Code to execute repeatedly as long as condition is true
}
for {
// Code to execute indefinitely until a break statement is encountered
}
Here's an example of using an if statement to check if a number is positive, negative, or zero.
1package main23import "fmt"45func main() {6num := 1078if num > 0 {9fmt.Println("Number is positive")10} else if num < 0 {11fmt.Println("Number is negative")12} else {13fmt.Println("Number is zero")14}15}
Number is positive
In this example, we use a switch statement to determine the day of the week based on an integer input.
1package main23import "fmt"45func main() {6day := 378switch day {9case 1:10fmt.Println("Monday")11case 2:12fmt.Println("Tuesday")13case 3:14fmt.Println("Wednesday")15case 4:16fmt.Println("Thursday")17case 5:18fmt.Println("Friday")19case 6:20fmt.Println("Saturday")21case 7:22fmt.Println("Sunday")23default:24fmt.Println("Invalid day")25}26}
Wednesday
Let's look at different types of loops in Go.
This example prints numbers from 1 to 5 using a basic for loop.
1package main23import "fmt"45func main() {6for i := 1; i <= 5; i++ {7fmt.Println(i)8}9}
1 2 3 4 5
This example uses a for loop to print numbers from 1 to 5, similar to a while loop in other languages.
1package main23import "fmt"45func main() {6i := 17for i <= 5 {8fmt.Println(i)9i++10}11}
1 2 3 4 5
This example demonstrates an infinite loop with a break statement to exit the loop.
1package main23import "fmt"45func main() {6i := 07for {8if i >= 5 {9break10}11fmt.Println(i)12i++13}14}
0 1 2 3 4
In the next section, we will delve deeper into if statements and explore more complex conditions and operators.