Week 2: Intermediate Topics (Days 8–14)
Focus: Deepen your understanding of Go with advanced data structures, error handling, and concurrency basics.
Day 8: Maps and Range
1. Working with Maps
Maps in Go store key-value pairs. You can create a map using the make
function or a map literal.
- Create a map:
m := make(map[string]int)
m["age"] = 30
m["height"] = 180
- Iterate over a map:
for key, value := range m {
fmt.Println(key, value)
}
- Output:
age 30
height 180
- Delete a map entry:
delete(m, "age")
Day 9: Error Handling
1. Go Error Interface
Go’s error handling uses an error
type. Functions that might return errors usually have this type as a return value.
- Returning an error:
package main
import (
"fmt"
"errors"
)
func checkAge(age int) (string, error) {
if age < 18 {
return "", errors.New("age is too low")
}
return "You are an adult", nil
}
func main() {
result, err := checkAge(15)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
- Output:
age is too low
Day 10: Variadic Functions and Defer
1. Variadic Functions
Go allows functions to accept a variable number of arguments using ...
syntax.
- Example:
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
func main() {
fmt.Println(sum(1, 2, 3, 4, 5))
}
- Output:
15
2. Defer
The defer
keyword delays the execution of a function until the surrounding function returns.
- Example:
package main
import "fmt"
func example() {
defer fmt.Println("Deferred!")
fmt.Println("Executing function")
}
func main() {
example()
}
- Output:
Executing function
Deferred!
Day 11: Interfaces and Polymorphism
1. Interfaces in Go
An interface in Go is a collection of method signatures. A type implements an interface by providing definitions for these methods.
- Example:
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Person struct {
name string
}
func (p Person) Speak() string {
return "Hello, my name is " + p.name
}
func main() {
var s Speaker = Person{name: "John"}
fmt.Println(s.Speak())
}
- Output:
Hello, my name is John
Day 12: Goroutines and Concurrency (Intro)
1. Understanding Goroutines
Goroutines allow you to run functions concurrently. They are lightweight and managed by Go’s runtime.
- Example:
package main
import "fmt"
func sayHello() {
fmt.Println("Hello, Goroutine!")
}
func main() {
go sayHello() // This runs in a separate goroutine
fmt.Println("Main function")
}
- Output:
Main function
Hello, Goroutine!
(Note: The order may vary since goroutines run concurrently.)
Day 13: Channels and Synchronization
1. Understanding Channels
Channels allow communication between goroutines. You can send and receive values via channels.
- Example:
package main
import "fmt"
func greet(ch chan string) {
ch <- "Hello, Go!"
}
func main() {
ch := make(chan string)
go greet(ch)
message := <-ch
fmt.Println(message)
}
- Output:
Hello, Go!
2. Channel Operations
- Sending data to a channel:
ch <- value
- Receiving data from a channel:
value := <- ch
Day 14: Select and Wait Groups
1. Select Statement
The select
statement allows you to wait on multiple channel operations.
- Example:
package main
import "fmt"
func sendMessage(ch chan string) {
ch <- "Hello, Channel!"
}
func main() {
ch := make(chan string)
go sendMessage(ch)
select {
case msg := <-ch:
fmt.Println(msg)
}
}
- Output:
Hello, Channel!
2. Wait Groups for Synchronization
sync.WaitGroup
is used to wait for a collection of goroutines to finish executing.
- Example:
package main
import (
"fmt"
"sync"
)
func task(wg *sync.WaitGroup) {
fmt.Println("Task started")
wg.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go task(&wg)
wg.Wait() // Wait until the task is done
fmt.Println("Task completed")
}
- Output:
Task started
Task completed
By the end of Week 2, you will have covered important Go concepts such as error handling, variadic functions, interfaces, goroutines, channels, and synchronization. These intermediate topics will give you the tools needed to write efficient and concurrent Go programs.
Leave a Reply