Sobes.tech
Senior

Which of the following code snippets contains an error or potential issue related to channel operations? Option 1 package main func main() { ch := make(chan int) ch <- 1 } Option 2 package main func main() { ch := make(chan int, 1) ch <- 1 } Option 3 package main func main() { ch := make(chan int, 1) ch <- 1 <-ch } Option 4 package main func main() { ch := make(chan int) close(ch) <-ch } Option 5 package main func main() { ch := make(chan int, 3) ch <- 4 }

sobes.tech AI

Answer from AI

The error is in Variant 1:

package main
func main() {
    ch := make(chan int)
    ch <- 1
}

Here, an unbuffered channel ch := make(chan int) is created. Sending to such a channel ch <- 1 blocks until someone reads from the channel. In this code, there is no receiver, so the program will deadlock forever.

Variant 2 is correct because the channel is buffered with size 1, and sending does not block if the buffer is not full.

Variant 3 is also correct: sending and receiving are balanced.

Variant 4 is correct: a closed channel can be read from, and the read will return the zero value without blocking.

Variant 5 is correct: buffer size 3, one value is sent, buffer is not full.

In summary, the problem is only in Variant 1 — blocking when sending to an unbuffered channel without a receiver.