How to Create Channel in Go: Simple Guide with Examples
In Go, you create a channel using the
make function with the syntax make(chan Type). Channels allow goroutines to communicate by sending and receiving values of the specified type.Syntax
To create a channel in Go, use the make function with the channel type. The syntax is:
chan Type: declares a channel that carries values ofType.make(chan Type): creates a new channel instance.
You can also create buffered channels by specifying a buffer size: make(chan Type, bufferSize).
go
ch := make(chan int) // Buffered channel example bufCh := make(chan string, 3)
Example
This example shows how to create a channel, send a value to it, and receive the value from it.
go
package main import ( "fmt" ) func main() { ch := make(chan string) // Create a channel of strings // Start a goroutine to send a message go func() { ch <- "Hello from channel!" }() // Receive the message from the channel msg := <-ch fmt.Println(msg) }
Output
Hello from channel!
Common Pitfalls
Common mistakes when creating or using channels include:
- Forgetting to use
maketo create the channel before use, which causes a runtime panic. - Sending or receiving on a nil channel, which blocks forever.
- Not closing channels when done, which can cause goroutines to wait indefinitely.
- Confusing buffered and unbuffered channels, leading to unexpected blocking behavior.
go
package main
func main() {
var ch chan int // nil channel, not created with make
// ch <- 1 // This will block forever and cause deadlock
ch = make(chan int) // Correct: create channel with make
go func() { ch <- 1 }() // Sending in a goroutine to avoid deadlock
<-ch // Receiving to avoid deadlock
}Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Create unbuffered channel | ch := make(chan Type) | Channel with no buffer, send and receive block until both are ready |
| Create buffered channel | ch := make(chan Type, size) | Channel with buffer size, send blocks only when buffer is full |
| Send value | ch <- value | Send value to channel, blocks if no receiver or buffer full |
| Receive value | value := <-ch | Receive value from channel, blocks if no value available |
| Close channel | close(ch) | Close channel to signal no more values will be sent |
Key Takeaways
Use make(chan Type) to create a new channel before using it.
Channels enable safe communication between goroutines by sending and receiving typed values.
Unbuffered channels block senders until receivers are ready; buffered channels allow limited asynchronous sends.
Always close channels when no more values will be sent to avoid blocking receivers.
Avoid using nil channels or forgetting to create channels with make to prevent deadlocks.