GO Channels and Communication 1 — Questions and Answers
Question 1: How do you create a buffered channel with capacity 5 in Go?
- make(chan int)
- make(chan int, 5) (Correct answer)
- chan int{5}
- new(chan int, 5)
Correct answer: make(chan int, 5)
`make(chan int, 5)` creates a buffered channel of integers with a buffer capacity of 5, allowing up to 5 sends without a corresponding receive.
Question 2: What happens when you send to a full buffered channel with no receiver?
- The send is discarded
- The send panics
- The goroutine blocks until space is available (Correct answer)
- The channel capacity doubles
Correct answer: The goroutine blocks until space is available
Sending to a full buffered channel blocks the sending goroutine until another goroutine receives and frees space in the buffer.
Question 3: What is the result of receiving from a closed, empty channel in Go?
- Panic
- Blocks forever
- Returns zero value and false (Correct answer)
- Returns zero value and true
Correct answer: Returns zero value and false
Receiving from a closed empty channel immediately returns the zero value of the channel's type and `false` for the ok variable.
Question 4: Which statement correctly closes a channel named `ch`?
- ch.close()
- close(ch) (Correct answer)
- ch = nil
- delete(ch)
Correct answer: close(ch)
The built-in `close(ch)` function closes a channel, signaling to receivers that no more values will be sent.
Question 5: What does `for v := range ch` do with a channel?
- Iterates over channel indices
- Receives values until the channel is closed (Correct answer)
- Sends values to the channel
- Reads channel metadata
Correct answer: Receives values until the channel is closed
`range` on a channel receives values one by one, blocking between receives, and exits the loop when the channel is closed and drained.
Question 6: What happens if you send on a closed channel?
- The value is silently dropped
- The send blocks indefinitely
- A panic occurs at runtime (Correct answer)
- A compile error occurs
Correct answer: A panic occurs at runtime
Sending to a closed channel causes a runtime panic: `send on closed channel`.
How do you create a buffered channel with capacity 5 in Go?