DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.

← Back to Questions
MediumTheory

Channel Operations: Send, Receive, Close, and Select

20 views

Problem Statement

Master all channel operations and their edge cases. This knowledge is essential for writing correct concurrent Go programs.

Channel Behavior Reference

OperationNil ChannelClosed ChannelOpen Channel
ch <- v (send)Blocks foreverPANICBlocks until received
<-ch (receive)Blocks foreverReturns zero, falseBlocks until sent
close(ch)PANICPANICCloses successfully

Key Interview Questions

Q1: What happens if you send to a closed channel?

ch := make(chan int)
close(ch)
ch <- 1  // PANIC: send on closed channel

Q2: What happens if you receive from a closed channel?

ch := make(chan int, 1)
ch <- 42
close(ch)
fmt.Println(<-ch) // 42
fmt.Println(<-ch) // 0 (zero value)

// Detect closed channel:
val, ok := <-ch
if !ok {
    fmt.Println("channel closed")
}

Q3: What happens if you send/receive on a nil channel?

var ch chan int  // nil
// ch <- 1       // Blocks forever
// <-ch          // Blocks forever
// close(ch)     // PANIC

Use case: Disable a select case dynamically by setting channel to nil.

Q4: How do you implement a non-blocking send?

select {
case ch <- value:
    fmt.Println("sent")
default:
    fmt.Println("channel full, dropped")
}

Q5: Buffered vs Unbuffered channels

// Unbuffered: synchronous handoff
ch := make(chan int)
// Sender blocks until receiver is ready

// Buffered: async up to capacity
ch := make(chan int, 10)
// Sender blocks only when buffer is full

Q6: How do you drain a channel after closing?

close(ch)
for val := range ch {
    process(val)
}
// range stops when channel is closed AND empty

Q7: Implement timeout with select

select {
case result := <-ch:
    fmt.Println("got result:", result)
case <-time.After(5 * time.Second):
    fmt.Println("timeout!")
}

Q8: Can you close a receive-only channel?

func consumer(ch <-chan int) {
    // close(ch)  // COMPILE ERROR
}
// Only the sender should close channels

Sample Test Cases

Case 1
Input
ch := make(chan int), go send(ch, 42)
Expected Output
Receiver gets 42 from channel
Case 2
Input
close(ch), val, ok := <-ch
Expected Output
ok is false after channel closed

No solutions yet

Be the first to share a solution for this question.

Comments (0)

Sign in to leave a comment.

No comments yet. Be the first to comment.

Stats

Views
20
Likes
0
Solutions
0
Comments
0

Category

Backend Engineering

Languages

Go