This tutorial aims to provide a comprehensive guide on how to work with 'for' and 'range' loops in Go, a statically typed, compiled programming language designed at Google.
By the end of this tutorial, you will have a solid understanding of how to use loops in Go. You will be able to control the flow of your programs by repeating blocks of code using 'for' and 'range' loops.
Basic knowledge of Go is required. If you're not familiar with Go, consider taking a beginner's course or reading introductory materials before proceeding with this tutorial.
In Go, the for
loop is the only looping construct. Here's how to write a simple for
loop:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
This will print the numbers 0 through 4. The loop continues to run as long as i
is less than 5.
The for
loop consists of three components: initialization (i := 0
), condition (i < 5
), and post (i++
).
The range
keyword in Go is used with for
loop to iterate over items of an array, slice, channel, or map. Here's how to use it:
nums := []int{2, 3, 4}
for index, num := range nums {
fmt.Println("index:", index, "num:", num)
}
This will print the index and value of each element in the 'nums' slice.
range
keyword when you need both the index and value in a loop.for
loop will eventually be false.for
LoopHere's an example of a basic for
loop:
// Initialize sum as 0
sum := 0
// Add numbers 1 through 5 to sum
for i := 1; i <= 5; i++ {
sum += i
}
// Print the sum
fmt.Println(sum) // Output: 15
In this example, the for
loop runs from 1 to 5, inclusive. The value of i
is added to sum
during each iteration, resulting in the sum of the numbers 1 through 5.
range
Loop Over a SliceHere's an example of a range
loop over a slice:
// Define a slice of integers
nums := []int{2, 3, 4}
// Iterate over the slice
for index, num := range nums {
fmt.Println("index:", index, "num:", num)
}
// Output:
// index: 0 num: 2
// index: 1 num: 3
// index: 2 num: 4
In this example, the range
keyword is used to iterate over the 'nums' slice. The loop prints the index and value of each element.
In this tutorial, we covered the basics of loops in Go, including the for
loop and the range
keyword. We looked at examples of how to use these constructs in different situations, and we discussed best practices for writing loops in Go.
Write a program in Go that finds the sum of an array of integers.
Write a program in Go that counts the number of occurrences of each character in a string.
Write a program in Go that prints the first 10 numbers of the Fibonacci sequence.
TBA
For further practice, try to solve problems on coding platforms like LeetCode and HackerRank using loops in Go. Remember, practice is key to mastering any programming concept.