I was wondering regarding the order of elements in golang channels. After running a few examples, it seems that the order in which the elements come off the channel is "last in first out". Am I right?
The following snippet is the example which I used. After running the code, the output is 20 10, while 10 was sent to the channel first and 20 last.
package main
import "fmt"
func multiply(c chan int, num int) {
c <- num * 10
}
func main() {
c := make(chan int)
go multiply(c, 1)
go multiply(c, 2)
v1 := <-c
v2 := <-c
fmt.Println(v1, v2)
}
Golang channels are not LIFO.
Values sent on the channel will be received whenever the receiver of the channel is ready. And if not then it will block. For managing that you can go for buffered channels.
Below code will check if the values are available to be received from the channel.
Working code on Go playground
Buffered Channels
Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:
In your case, it depends on which go routine will send the value on the channel first. The values that you are printing completely depends on the go routines.
For more information go through Golang Channels