...
Golang

Week 3: Advanced Go Topics – Concurrency, Testing & Libraries

Week 3: Advanced Topics (Days 15–21)

Focus: Dive deep into advanced concurrency patterns, Go’s standard library, testing, and memory management.


Day 15: Advanced Goroutine Patterns

1. Concurrency Patterns

Go’s goroutines and channels make it easy to implement advanced concurrency patterns.

  • Worker Pool:
    A worker pool is a set of goroutines that execute tasks concurrently. The main goroutine sends tasks to the pool, and workers process them.
  package main

  import "fmt"

  func worker(id int, jobs <-chan int, results chan<- int) {
      for j := range jobs {
          fmt.Printf("Worker %d started job %d\n", id, j)
          results <- j * 2
      }
  }

  func main() {
      jobs := make(chan int, 100)
      results := make(chan int, 100)

      for w := 1; w <= 3; w++ {
          go worker(w, jobs, results)
      }

      for j := 1; j <= 5; j++ {
          jobs <- j
      }
      close(jobs)

      for a := 1; a <= 5; a++ {
          fmt.Println(<-results)
      }
  }

2. Handling Deadlocks and Race Conditions

Deadlocks occur when two or more goroutines are waiting for each other to release resources, while race conditions occur when multiple goroutines access shared memory without proper synchronization.

  • Avoid deadlock: Ensure that channels are properly closed, and use select for handling multiple channel operations.

Day 16: Go’s Standard Library (Part 1)

1. net/http Package

Use Go’s net/http package to build HTTP servers and make requests.

  • Example (HTTP Server):
  package main

  import (
      "fmt"
      "net/http"
  )

  func handler(w http.ResponseWriter, r *http.Request) {
      fmt.Fprintln(w, "Hello, World!")
  }

  func main() {
      http.HandleFunc("/", handler)
      http.ListenAndServe(":8080", nil)
  }

2. io and os Packages

Use io for reading and writing files, and os for interacting with the operating system.

  • File Manipulation Example:
  package main

  import (
      "fmt"
      "os"
  )

  func main() {
      file, err := os.Create("example.txt")
      if err != nil {
          fmt.Println("Error:", err)
          return
      }
      defer file.Close()
      file.WriteString("Hello, Go!")
  }

3. fmt Package

The fmt package allows formatted I/O operations.

  • Example:
  fmt.Printf("My name is %s and I am %d years old\n", "Alice", 25)

Day 17: Go’s Standard Library (Part 2)

1. strings and strconv Packages

  • strings Package: Manipulate and search for substrings.
  import "strings"
  fmt.Println(strings.ToUpper("hello"))
  • strconv Package: Convert between strings and basic data types.
  import "strconv"
  num, _ := strconv.Atoi("42")
  fmt.Println(num)

2. time Package

Use the time package to handle time and dates.

  • Example:
  import "time"
  currentTime := time.Now()
  fmt.Println("Current time:", currentTime)

3. math Package

Perform advanced mathematical operations.

  • Example:
  import "math"
  fmt.Println(math.Sqrt(16)) // Output: 4

Day 18: Testing in Go

1. Testing with the testing Package

Go has built-in support for testing. Use the testing package to write unit tests for your code.

  • Example:
  package main

  import "testing"

  func Add(a, b int) int {
      return a + b
  }

  func TestAdd(t *testing.T) {
      result := Add(2, 3)
      if result != 5 {
          t.Errorf("Expected 5, but got %d", result)
      }
  }

2. Benchmark Testing

Use Go’s built-in benchmarking support to measure performance.

  • Example:
  func BenchmarkAdd(b *testing.B) {
      for i := 0; i < b.N; i++ {
          Add(2, 3)
      }
  }

Day 19: Dependency Management and Modules

1. Go Modules

Go introduced modules to manage dependencies in Go 1.11. Use go mod to manage your project.

  • Initialize a Go module:
  go mod init mymodule
  • Importing Dependencies:
  go get github.com/some/package

2. Working with Multiple Modules

Go modules allow you to easily manage and use multiple dependencies across projects.


Day 20: Reflection and Type Assertion

1. Reflection

Reflection in Go allows inspecting and manipulating types at runtime.

  • Example:
  package main

  import (
      "fmt"
      "reflect"
  )

  func main() {
      var x float64 = 3.4
      fmt.Println("Type:", reflect.TypeOf(x))
      fmt.Println("Value:", reflect.ValueOf(x))
  }

2. Type Assertions

Type assertions allow you to access the underlying type of an interface.

  • Example:
  var i interface{} = "Hello"
  s := i.(string) // Type assertion
  fmt.Println(s)

Day 21: Memory Management and Garbage Collection

1. Go’s Memory Model

Go uses garbage collection (GC) to manage memory automatically, freeing up memory that is no longer in use.

  • Memory Optimization:
    Use Go’s built-in profiler to find memory leaks and optimize usage.
  • Example:
  package main

  import "fmt"

  func main() {
      var x = make([]int, 1000000)
      fmt.Println(x[:10])
  }

Go handles memory allocation and deallocation efficiently to prevent memory leaks, and its garbage collector minimizes overhead.


By the end of Week 3, you will be well-versed in advanced Go topics such as concurrency patterns, working with Go’s standard library, testing your code, and understanding memory management. These skills are essential for writing high-performance, scalable Go programs.

Leave a Reply

Your email address will not be published. Required fields are marked *