Module 2: Channels (The Communication Pipe)
📚 Module 2: Channels
Course ID: GO-110
Subject: The Communication Pipe
Goroutines allow you to do things in the background. But how do you get data back from them? Or how do you tell them to stop? We use Channels.
🏗️ Step 1: The “Pipe” Concept
A channel is like a physical Pipe between two Goroutines.
- One Gopher puts a ball (Data) into the pipe.
- The ball rolls through.
- The other Gopher catches the ball on the other side.
🧩 The Analogy: The Subway Tube
- Imagine a tube at a bank drive-thru.
- You put your check in the tube and press a button.
- It arrives at the teller.
- The teller puts your cash in and sends it back.
🏗️ Step 2: Synchronization (The “Waiting”)
Channels are Blocking by default.
- If you try to catch a ball but the pipe is empty, you Wait until someone puts a ball in.
- If you try to put a ball in but nobody is there to catch it, you Wait until someone arrives.
Why is this good? It means you don’t need complex “Locks” or “Mutexes.” The gophers automatically wait for each other!
🏗️ Step 3: In Code
func main() {
// 1. Create a pipe for strings
messages := make(chan string)
// 2. Start a background task
go func() {
// 3. Put a message in the pipe
messages <- "Ping!"
}()
// 4. Catch the message
msg := <-messages
fmt.Println(msg)
}🥅 Module 2 Review
- Channel: A safe way to share data between background tasks.
<-(Arrow): The direction the data is moving.- make(chan type): How we build a new channel.
:::tip Senior Tip Go’s philosophy is: “Don’t communicate by sharing memory; share memory by communicating.” Use Channels instead of shared variables to avoid bugs! :::