What is a channel?
- Go course
- Intermediate
- Lesson 7/80
- 4 min
Learn that a channel is a communication tool between goroutines.
What is a channel?
A channel is a typed conduit for communication and synchronization between goroutines. One goroutine sends data on a channel, another receives it; Go handles the transfer safely and synchronously.
Channels are the core of Go's philosophy: do not communicate by sharing memory; share memory by communicating. You create one with make(chan int).
Channel philosophy
Go's famous slogan is: do not communicate by sharing memory; instead, share memory by communicating. The channel is the tool for this philosophy.
If multiple goroutines access a shared variable a race occurs. With a channel data passes through one goroutine at a time and synchronization is automatic. This enables lock-free designs.
Practice Message via channel
Inside main, add a make(chan string) call and print channel ready with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch := make(chan string)
go func() { ch <- "channel hazır" }()
fmt.Println(<-ch)
}Expected output
channel hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a channel for?
- Communication between goroutines Correct answer
- To declare variables
- To write loops
- To catch errors
Explanation: communication between goroutines.
2 Creating a channel
ch := ____
ch <- 42
ch := make(chan int)
ch <- 42
Explanation: new returns a pointer, it does not create a channel.
3 Match channel concepts
| Term | Meaning |
|---|---|
channel |
Communication pipe |
make |
Creation function |
<- |
Send/receive operator |
chan |
Type keyword |