Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Loops in Golang

In Go (often referred to as Golang), loops play a fundamental role in controlling the flow of a program. Go simplifies looping constructs by providing only the for loop, but it offers it with enough flexibility to cover a range of scenarios.

Here's a step-by-step guide to understanding loops in Go:

1. Basic for Loop

The basic structure of the for loop is:

for initialization; condition; post {
    // code to execute during each iteration
}
  • Initialization: Executes once at the beginning of the loop.
  • Condition: Checked before every iteration. If it's true, the loop continues; if false, the loop terminates.
  • Post: Executes after every iteration.

Example:

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}

2. Condition-only for Loop

This functions like the while loop in other languages.

for condition {
    // code to execute as long as condition is true
}

Example:

package main

import "fmt"

func main() {
    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
}

3. Infinite for Loop

Omitting the condition results in an infinite loop. This loop will run forever, unless externally interrupted or explicitly broken using a statement like break.

for {
    // code to execute indefinitely
}

Example:

package main

import "fmt"

func main() {
    i := 0
    for {
        fmt.Println(i)
        i++
        if i >= 5 {
            break
        }
    }
}

4. for Loop with range

Used to iterate over elements in collections like slices, arrays, strings, maps, and channels.

for key, value := range collection {
    // code to execute for each element in the collection
}

Example:

Iterating over a slice:

package main

import "fmt"

func main() {
    nums := []int{1, 2, 3, 4, 5}
    for index, value := range nums {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

Iterating over a string:

package main

import "fmt"

func main() {
    str := "GoLang"
    for index, char := range str {
        fmt.Printf("Index: %d, Rune: %c\n", index, char)
    }
}

Tips:

  • Using the Blank Identifier: If you don't need the index or value while ranging over a collection, you can use the blank identifier _:
for _, value := range nums {
    fmt.Println(value)
}
  • Nested Loops: Just like other programming languages, you can nest loops inside each other.
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        fmt.Printf("(%d, %d) ", i, j)
    }
    fmt.Println()
}

That wraps up a fundamental introduction to loops in Golang. Remember, practice is essential. By working with loops in different scenarios, you'll become more comfortable and efficient in using them in your programs.

  1. Types of loops in Golang:

    • Description: Overview of the types of loops in Golang, including for loops, while loops (implemented using for), and range loops for iterating over collections.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          // Standard for loop
          for i := 1; i <= 5; i++ {
              fmt.Println("For Loop:", i)
          }
      
          // While loop (implemented using for)
          j := 1
          for j <= 5 {
              fmt.Println("While Loop:", j)
              j++
          }
      
          // Range loop for iterating over collections
          numbers := []int{1, 2, 3, 4, 5}
          for index, value := range numbers {
              fmt.Printf("Index: %d, Value: %d\n", index, value)
          }
      }
      
  2. How to use for loops in Golang:

    • Description: Demonstration of the basic for loop in Golang, including loop initialization, condition, and iteration.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          for i := 1; i <= 5; i++ {
              fmt.Println(i)
          }
      }
      
  3. Golang while loop examples:

    • Description: Implementing a while loop in Golang using the for loop syntax.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          i := 1
          for i <= 5 {
              fmt.Println(i)
              i++
          }
      }
      
  4. Iterating over arrays and slices in Golang:

    • Description: Using for loops to iterate over arrays and slices in Golang.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          // Iterating over an array
          numbers := [3]int{1, 2, 3}
          for i := 0; i < len(numbers); i++ {
              fmt.Println("Array Element:", numbers[i])
          }
      
          // Iterating over a slice
          names := []string{"Alice", "Bob", "Charlie"}
          for index, name := range names {
              fmt.Printf("Index: %d, Name: %s\n", index, name)
          }
      }
      
  5. Using range in Golang loops:

    • Description: Utilizing the range keyword for concise iteration over arrays, slices, and other iterable types in Golang.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          numbers := []int{1, 2, 3, 4, 5}
          for index, value := range numbers {
              fmt.Printf("Index: %d, Value: %d\n", index, value)
          }
      }
      
  6. Nested loops in Golang:

    • Description: Implementing nested loops, where one loop is contained within another, in Golang.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          for i := 1; i <= 3; i++ {
              for j := 1; j <= 3; j++ {
                  fmt.Printf("(%d, %d) ", i, j)
              }
              fmt.Println()
          }
      }
      
  7. Looping through maps in Golang:

    • Description: Iterating over key-value pairs in a map using a for loop in Golang.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          person := map[string]string{
              "Name":  "John",
              "Age":   "30",
              "City":  "New York",
              "Role":  "Developer",
          }
      
          for key, value := range person {
              fmt.Printf("Key: %s, Value: %s\n", key, value)
          }
      }
      
  8. Infinite loops and breaking out of them in Golang:

    • Description: Demonstrating the creation of an infinite loop and breaking out of it using a break statement.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          i := 1
          for {
              fmt.Println(i)
              i++
              if i > 5 {
                  break
              }
          }
      }