Channel with make
- Go course
- Intermediate
- Lesson 8/80
- 4 min
Learn to create a channel with make.
Channel with make
Channels are created with make: ch := make(chan int). This makes an unbuffered channel; the sender blocks until a receiver is ready.
The channel type uses chan + element type: chan int, chan string, chan struct{}. chan struct{} is used for signals (no data).
Channel types
Channel types vary by element type and each serves a different purpose:
chan int— integer channel for numberschan string— text channel for messageschan struct{}— signal channel (no data), notification onlychan<- int— send-only, restricts in function parameters
One-way channels restrict direction in function parameters; this prevents accidental receive or send on the wrong side.
Practice Create a channel and print
Inside main, add a make(chan string) call and print channel opened 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 açıldı" }()
fmt.Println(<-ch)
}Expected output
channel açıldı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What kind of channel does make(chan int) create?
- Buffered
- Unbuffered Correct answer
- Asynchronous
- One-way
Explanation: unbuffered. For a buffered channel use make(chan int, n).
2 Channel type
ch := make(____)
ch := make(chan int)
Explanation: chan comes first, type after.
3 Match channel types
| Term | Meaning |
|---|---|
chan int |
Integer |
chan string |
Text |
chan struct{} |
Signal |
chan<- int |
Send-only |