Answer the question
In order to leave comments, you need to log in
Why do channels in go work so strangely?
package main
import "fmt"
func main() {
fmt.Println("Start")
// создание канала и получение из него данных
fmt.Println(<-createChan(5)) // блокировка
fmt.Println("End")
}
func createChan(n int) chan int{
ch := make(chan int) // создаем канал
ch <- n // отправляем данные в канал
return ch // возвращаем канал
}
Answer the question
In order to leave comments, you need to log in
Everything is simple.
1. If the channel is without a buffer, then when reading from it, the program will block at this place until someone in another goroutine writes a value to this channel. Accordingly, the write operation will also block until someone wants to read from the pipe.
2. If the channel has a buffer and there is still space left in the buffer, then the write operation will not block, but will immediately return control. The read operation will also not block if there is any data in the buffer. If the buffer is full, then the recording will behave the same as in step 1. If the buffer is empty, then reading will behave the same as in n1.
In your program, a channel is created inside createChan and immediately written to it. This entry is being locked, waiting for someone to read from the channel. But reading from the channel will only happen when you exit the function, so the program stops forever.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question