Answer the question
In order to leave comments, you need to log in
Channels in golang, but what about that one?
package main
import "fmt"
func main() {
intCh := make(chan int, 2)
go factorial(5, intCh)
fmt.Println(<-intCh)
fmt.Println("The End")
}
func factorial(n int, ch chan<- int){
result := 1
for i := 1; i <= n; i++{
result *= i
}
ch <- result
}
Answer the question
In order to leave comments, you need to log in
There is only one channel in the code: intCh, when factorial is called, the channel is passed by reference (it is the only way it is passed) and inside factorial this single channel is called ch and, in addition, it has a restriction that this channel can only be used to output to it (the restriction is imposed in function parameter declarations).
No magic - the channel was announced, transmitted, read from it.
The channel is passed by reference. The fact that the channel in the function is unidirectional does not change or copy the original channel in any way, it just cannot be used inside the function in any other way (the channel for writing cannot be read, the channel for reading cannot be written)
https://play.golang.com/p /v00VjMZHqGu
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question