I’ve read https://go.dev/blog/pipelines and there’re two functions:
// move numbers into a channel
func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
// square those numbers take from "in" channel
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}
and inside main function
in := gen(2, 3)
// Distribute the sq work across two goroutines that both read from in.
c1 := sq(in)
c2 := sq(in)
I thought that sq
is just a normal function, so c1 must take all values from “in” channel and c2 is empty, but it was not.
So this mean a goroutine inside a function still can get out of that function scope and return to main routine to execute next command ?
New contributor
iwa2no is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.