Syntax Error Patterns
Common Channel Syntax Errors in Go
1. Uninitialized Channel Errors
var ch chan int
ch <- 42 // Panic: send on nil channel
Correct Initialization
ch := make(chan int)
// or
var ch = make(chan int)
2. Directional Channel Misuse
// Incorrect channel direction assignment
var sendOnly chan<- int = make(chan int) // Compilation error
var receiveOnly <-chan int = make(chan int) // Compilation error
Proper Channel Direction
sendCh := make(chan<- int)
receiveCh := make(<-chan int)
Channel Operation Syntax Errors
3. Sending to Closed Channel
ch := make(chan int)
close(ch)
ch <- 42 // Panic: send on closed channel
4. Receiving from Closed Channel
ch := make(chan int)
close(ch)
value, ok := <-ch // Proper way to handle closed channel
if !ok {
fmt.Println("Channel is closed")
}
Deadlock Scenarios
graph TD
A[Goroutine 1] -->|Blocking Send| B[Unbuffered Channel]
B -->|No Receiver| C[Deadlock]
5. Unbuffered Channel Deadlock
ch := make(chan int)
ch <- 42 // Blocks forever without receiver
Error Prevention Patterns
Error Type |
Prevention Strategy |
Nil Channel |
Always initialize with make() |
Closed Channel |
Check channel state before sending |
Directional Mismatch |
Use explicit channel type declarations |
Deadlock |
Use buffered channels or goroutine receivers |
6. Select Statement Error Handling
ch1 := make(chan int)
ch2 := make(chan string)
select {
case v := <-ch1:
fmt.Println("Received from ch1:", v)
case v := <-ch2:
fmt.Println("Received from ch2:", v)
default:
fmt.Println("No channel ready")
}
Advanced Error Scenarios
7. Goroutine Channel Leaks
func channelLeak() {
ch := make(chan int)
go func() {
// No closing or receiving mechanism
// Potential goroutine and channel leak
}()
}
Recommended Practice
func safeChannelUsage() {
ch := make(chan int, 1) // Buffered channel
go func() {
defer close(ch)
ch <- 42
}()
value := <-ch
fmt.Println(value)
}
Key Takeaways
- Always initialize channels before use
- Understand channel directions
- Handle closed channels gracefully
- Prevent potential deadlocks
- Use
select
for complex channel operations
By recognizing these syntax error patterns, developers can write more robust and error-free concurrent Go code.