Go Routines: Super Simple
Go routines let you do things at the same time (concurrently). Think of it like having two people cooking in the kitchen at the same time, each doing a different task.
Super Simple Go Routine Example:
package main
import (
"fmt"
"time"
)
func cook(name string) {
fmt.Println("Cooking started:", name)
time.Sleep(2 * time.Second)
fmt.Println("Cooking finished:", name)
}
func main() {
go cook("Pizza") // Start cooking pizza in a new go routine
cook("Pasta") // Meanwhile, start cooking pasta in the main go routine
}
Here, go cook("Pizza")
starts cooking pizza in a new go routine, and immediately after, the main go routine starts cooking pasta. They happen at the same time.
Channels: Like Passing Notes
Channels are like passing notes between people. If one person writes a note (sends data) and gives it to another person (another go routine), the second person can read this note (receive data).
Super Simple Channel Example:
package main
import "fmt"
func main() {
messages := make(chan string)
go func() {
messages <- "Hello" // Sending a note
}()
msg := <-messages // Receiving the note
fmt.Println(msg)
}
In this example, a new go routine sends "Hello"
into the messages
channel. The main go routine then receives this message and prints it. It's like the new go routine is passing a note saying "Hello"
to the main go routine.
In a Nutshell
- Go Routines: Doing multiple tasks at the same time. Like multiple chefs cooking different dishes in a kitchen.
- Channels: A way to send data from one task (go routine) to another. Like passing notes between these chefs to coordinate.
Both of these features make Go powerful for handling multiple tasks efficiently and communicating between them.