output: 10 is the data from channel
How? We are passing data in the function in the line next to the go func_name(c)
then how this go-routine is getting data from the c <- 10
To understand this we have to dig deeper into the internal working of channels.
Let’s break the whole code execution into steps and see what's going on more clearly.
1: We declared a function func_name()
which will print the data of the channel c chan int
2: We declare the main function
3: We now created a channel c:= make(chan int)
4: Now we passed the channel to the func_name(c)
go-routine. but go-routine is blocked as of now, due to no data in the channel.
5: What happened is, we have two go-routines now. main
and func_name
6: We are putting data to channel c <- 10
, this blocked our main
go-routine and waiting for func_name
to read the data. Now we have pushed data to our channel, the go scheduler now schedules func_name
go-routine and it will read and print the value, now the execution of func_name
is over.
7: Now the main go-routine unblocks and completes execution.
Hope you now have a clear idea of how channels work.
That’s all for this one. I will be writing some more about channels in my next article.
Thank you for reading.