Junior — Middle
How is sequential data reading from a channel implemented?
sobes.tech AI
Answer from AI
In Go, sequential reading of data from a channel is performed using the receive operator <-. When you read from a channel, execution blocks until a value appears in the channel. This provides sequential and synchronous access to data.
Example of reading from a channel:
ch := make(chan int)
go func() {
ch <- 42 // send value to the channel
}()
value := <-ch // read value from the channel, blocking if no data
fmt.Println(value) // will output 42
If you need to read multiple values sequentially, you can use a for range loop:
for v := range ch {
fmt.Println(v)
}
This loop will read from the channel until it is closed.